![](/img/trans.png)
[英]Python minidom: How to get parent nodes of those first child nodes that have the same attribute values
[英]python minidom - get data from parent nodes with the same name
我有一個具有以下結構的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>
...
我想獲得所有物品的清單以及有關其父母的信息。 例如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
我找到了答案:
def read_region(self, xml):
doc = minidom.parse(xml)
node = doc.getElementsByTagName("Zone")
data_array = []
for zone in node:
zone_child = zone.getElementsByTagName("Zone")
if len(zone_child)==0:
print(zone.getAttribute("name"))
subzone_parent = zone.parentNode
zone_parent = subzone_parent.parentNode
print(zone_parent.getAttribute("name"))
subzone_parent_parent = zone_parent.parentNode
zone_parent_parent = subzone_parent_parent.parentNode
print(zone_parent_parent.getAttribute("name"))
subzone_top = zone_parent_parent.parentNode
zone_top = subzone_top.parentNode
try:
print(zone_top.getAttribute("name"))
except Exception,e:
print("DEBUG")
我檢查“區域”節點中是否沒有子節點,並獲取該節點的每個父節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.