繁体   English   中英

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

[英]parsing xml containing default namespace to get an element value using lxml

我有一个像这样的 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM