我有一个具有以下结构的 xml 文件:
<zone id=1 name=one>
<subzone>
<zone id=2 name=subone>
...
<item>
<item>
...
<zone id=1 name=two>
<subzone>
<zone id=2 name=subtwo>
...
<item>
<item>
...
我想获取所有项目的列表以及有关其 parent 的信息。例如 - item, zone_id=1, zone_name=two, subzone_id=2, subzone_name=subtwo
。
对于items
组来说,zone
节点的数量是不同的。
我可以获得所有区域的列表:
def read_region(self, xml):
doc = minidom.parse(xml)
node = doc.getElementsByTagName("zone")
for zone in node:
print(zone.getAttribute("name"))
如果有很多具有相同节点名的节点,如何从特定节点获取数据?或者是否可以获取某个元素的所有父节点的信息?
最佳答案
您问两个问题:
- 如何从多个同名元素中获取特定元素?
如何获取给定元素的所有父元素?
要获取特定元素,您必须确定该元素的不同之处。它可能是与另一个可唯一识别的元素的关系。
您可以通过重复调用
node.getparent()
来获取元素的所有父元素,如下所示。请参阅http://lxml.de/api/lxml.etree._Element-class.html 。def get_parents(element): ancestors = [] parent = element.getparent() while parent != None: ancestors.append(parent) parent = parent.getparent() return ancestors
关于python minidom - 从同名的父节点获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28980135/