【发布时间】:2021-05-11 18:42:41
【问题描述】:
我有一个包含多个级别的 XML。每个级别都可以附加命名空间。我想find 一个我知道其名称但不知道其名称空间的特定元素。例如:
my_file.xml
<?xml version="1.0" encoding="UTF-8"?>
<data xmlns="aaa:bbb:ccc:ddd:eee">
<country name="Liechtenstein" xmlns="aaa:bbb:ccc:liechtenstein:eee">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore" xmlns="aaa:bbb:ccc:singapore:eee">
<continent>Asia</continent>
<holidays>
<christmas>Yes</christmas>
</holidays>
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama" xmlns="aaa:bbb:ccc:panama:eee">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
import lxml.etree as etree
tree = etree.parse('my_file.xml')
root = tree.getroot()
cntry_node = root.find('.//country')
上面的find 不会向cntry_node 返回任何内容。在我的真实数据中,层次比这个例子更深。 lxml 文档讨论了命名空间。当我这样做时:
root.nsmap
我看到了:
{None: 'aaa:bbb:ccc:ddd:eee'}
如果有人可以解释如何访问完整的nsmap 和/或如何将其用于find 特定元素?非常感谢。
【问题讨论】:
-
@MathiasMüller @mzjn 也许我还是不明白这里的命名空间概念。我假设在解析 XML 文件时,命名空间存储在
nsmap中。因此,我们可以访问它。从这里的答案看来,我必须手动定义这个文件?对于大型 XML 文件来说,这需要大量工作。