解析包含默认名称空间的xml以使用lxml获取元素值 [英] parsing xml containing default namespace to get an element value using lxml

查看:177
本文介绍了解析包含默认名称空间的xml以使用lxml获取元素值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的xml字符串

I have a xml string like this

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

I want to extract all the urls present inside <loc> node i.e http://www.example.org/sitemap_1.xml.gz

我尝试了这段代码,但没有发声

I tried this code but it didn't word

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

我试图检查我的根节点格式是否正确.我尝试了这个,并获得了与str1相同的字符串

I tried to check if my root node is formed correctly. I tried this and get back the same string as 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具有默认的名称空间,此处声明为不带前缀的名称空间:

This is a common error when dealing with XML having default namespace. Your XML has default namespace, a namespace declared without prefix, here :

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

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

Note that not only element where default namespace declared is in that namespace, but all descendant elements inherit ancestor default namespace implicitly, unless otherwise specified (using explicit namespace prefix or local default namespace that point to different namespace uri). That means, in this case, all elements including loc are in default namespace.

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

To select element in namespace, you'll need to define prefix to namespace mapping and use the prefix properly in the 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>

这篇关于解析包含默认名称空间的xml以使用lxml获取元素值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆