解析包含默认命名空间的 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
在内的所有元素都在默认命名空间中。
对于命名空间中的 select 元素,您需要定义前缀到命名空间映射并在 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 这样的字符串
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
在内的所有元素都在默认命名空间中。
对于命名空间中的 select 元素,您需要定义前缀到命名空间映射并在 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>