我有一个这样的xml字符串
str1 = """<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>
http://www.example.org/sitemap_1.xml.gz
</loc>
<lastmod>2015-07-01</lastmod>
</sitemap>
</sitemapindex> """
我想提取<loc>
节点中的所有url
i、 ehttp://www.example.org/sitemap_1.xml.gz
我试过这个密码,但没用
^{pr2}$我试图检查根节点的格式是否正确。我试过了,得到了和str1相同的字符串
etree.tostring(root)
'<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n<sitemap>\n<loc>http://www.example.org/sitemap_1.xml.gz</loc>\n<lastmod>2015-07-01</lastmod>\n</sitemap>\n</sitemapindex>'
这是处理具有默认命名空间的XML时的常见错误。您的XML具有默认名称空间,即声明时没有前缀的名称空间,此处:
请注意,不仅声明了默认命名空间的元素位于该命名空间中,而且所有子元素都隐式继承祖先默认命名空间,除非另有指定(使用显式命名空间前缀或指向不同命名空间uri的本地默认命名空间)。这意味着,在本例中,包括
loc
的所有元素都在默认名称空间中。在要选择命名空间中的元素,需要定义前缀到命名空间映射,并在XPath中正确使用前缀:
^{pr2}$输出:
相关问题 更多 >
编程相关推荐