gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:54:22 29 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 - 解析包含默认命名空间的 xml 以使用 lxml 获取元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31177707/

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