如何在null命名空间节点上使用lxml中的xpath?

使用lxml处理xml文档中某些节点上缺少命名空间的最佳方法是什么?我是否应首先修改所有无命名节点以添加“gmd”名称,然后将树属性更改为将名称 http://www.isotc211.org/2005/gmd命名为“gmd”?如果是这样,有没有一个干净的方法来做lxml或其他相对干净/安全的东西吗?
from lxml import etree
nsmap = charts_tree.nsmap
nsmap.pop(None) # complains without this on the xpath with
# TypeError: empty namespace prefix is not supported in XPath
len (charts_tree.xpath('//*/gml:Polygon',namespaces=nsmap))
# 1180
len (charts_tree.xpath('//*/DS_DataSet',namespaces=nsmap))
# 0 ... Bummer!
len (charts_tree.xpath('//*/DS_DataSet'))
# 0 ... Also a bummer

例如http://www.charts.noaa.gov/ENCs/ENCProdCat_19115.xml

<DS_Series xmlns="http://www.isotc211.org/2005/gmd" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:gsr="http://www.isotc211.org/2005/gsr" xmlns:gss="http://www.isotc211.org/2005/gss" xmlns:gts="http://www.isotc211.org/2005/gts" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.isotc211.org/2005/gmd http://schemas.opengis.net/iso/19139/20070417/gmd/gmd.xsd">
<composedOf>
    <DS_DataSet>
        <has>
            <MD_Metadata>
                <parentIdentifier>
                    <gco:CharacterString>NOAA ENC Product Catalog</gco:CharacterString>
                </parentIdentifier>
...
<EX_BoundingPolygon>
    <polygon>
        <gml:Polygon gml:id="US1AK90M_P1">
            <gml:exterior>
                <gml:LinearRing>
                    <gml:pos>67.61505 -178.99979</gml:pos>
                    <gml:pos>73.99999 -178.99979</gml:pos>
...
                    <gml:pos>64.99997 -178.99979</gml:pos>
                    <gml:pos>67.61505 -178.99979</gml:pos>
                </gml:LinearRing>
我相信你的DS_DataSet是由于在DS_Series中(暗示默认命名空间为“http://www.isotc211.org/2005/gmd”)携带一个命名空间.

尝试将其映射到您的命名空间字典中(您可以首先测试打印以查看它是否已经存在,否则添加它并通过新键引用命名空间).

nsmap['some_ns'] = "http://www.isotc211.org/2005/gmd"
len (charts_tree.xpath('//*/some_ns:DS_DataSet',namespaces=nsmap))

哪个成了:

nsmap['gmd'] = nsmap[None]
nsmap.pop(None)
len(charts_tree.xpath('//*/gmd:DS_DataSet',namespaces=nsmap))

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念