您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

在处理具有名称间的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>
其他 2022/1/1 18:38:26 有474人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶