使用 lxml 解析包含默认命名空间的 xml 以获取元素值

2024-02-29

我有一个像这样的 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>节点 IEhttp://www.example.org/sitemap_1.xml.gz

我尝试了这段代码,但它没有字

from lxml import etree
root = etree.fromstring(str1)
urls = root.xpath("//loc/text()")
print urls
[]

我尝试检查我的根节点是否正确形成。我尝试了这个并返回与 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 有默认命名空间,这是一个没有前缀的命名空间,如下所示:

<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

请注意,不仅声明默认命名空间的元素位于该命名空间中,而且所有后代元素都隐式继承祖先默认命名空间,除非另有指定(使用指向不同命名空间 uri 的显式命名空间前缀或本地默认命名空间)。这意味着,在这种情况下,所有元素包括loc位于默认命名空间中。

要选择名称空间中的元素,您需要定义名称空间映射的前缀,并在 XPath 中正确使用前缀:

from lxml import etree
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>'''
root = etree.fromstring(str1)

ns = {"d" : "http://www.sitemaps.org/schemas/sitemap/0.9"}
url = root.xpath("//d:loc", namespaces=ns)[0]
print etree.tostring(url)

output :

<loc xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        http://www.example.org/sitemap_1.xml.gz
    </loc>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 lxml 解析包含默认命名空间的 xml 以获取元素值 的相关文章

随机推荐