gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:52:22 24 4
gpt4 key购买 nike

我有一个这样的 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节点
http://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)

输出:
<loc xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
http://www.example.org/sitemap_1.xml.gz
</loc>

关于python - 使用 lxml 解析包含默认命名空间的 xml 以获取元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com