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

Python 使用lxml解析包含默认名称空间的xml以获取元素值,python,xml,lxml,elementtree,default-namespace,Python,Xml,Lxml,Elementtree,Default Namespace,我有这样一个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> </sitema

我有这样一个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> """
我试图检查我的根节点的格式是否正确。我尝试了这个,得到了与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>'
etree.tostring(根)
“\n\nhttp://www.example.org/sitemap_1.xml.gz\n2015-07-01\n\n'

处理具有默认命名空间的XML时,这是一个常见错误。您的XML具有默认名称空间,该名称空间声明时没有前缀,如下所示:

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

<loc xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        http://www.example.org/sitemap_1.xml.gz
    </loc>

http://www.example.org/sitemap_1.xml.gz
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>