Python minidom:如何获取具有相同属性值的第一个子节点的父节点
我有一个巨大的xml文件。我在此仅举一个例子:Python minidom:如何获取具有相同属性值的第一个子节点的父节点,python,xml,minidom,Python,Xml,Minidom,我有一个巨大的xml文件。我在此仅举一个例子: <?xml version="1.0"?> <data yahoo="state"> <country name="Cambodia"> <neighbor name="Thailand" direction="W"/> <neighbor name="Vietnam" towards="E"/> </country> <country name="Sin
<?xml version="1.0"?>
<data yahoo="state">
<country name="Cambodia">
<neighbor name="Thailand" direction="W"/>
<neighbor name="Vietnam" towards="E"/>
</country>
<country name="Singapore">
<neighbor name="Malaysia" dimension="N"/>
</country>
<country name="Panama">
<neighbor name="Costa Rica" dimension="W"/>
<neighbor name="Colombia" towards="E"/>
</country>
</data>
在字典中映射相邻节点,并按其
方向
值对它们进行分组:
from collections import defaultdict
by_direction = defaultdict(list)
# map directions
for neighbor in xmldoc.getElementsByTagName("neighbor"):
if not 'direction' in neighbor.attributes:
continue
direction = neighor.attributes['direction'].value
by_direction[direction].append(neighbor)
# look up by dimension:
for neighbor in xmldoc.getElementsByTagName("neighbor"):
if not 'dimension' in neighbor.attributes:
continue
dimension = neighor.attributes['dimension'].value
print neighbor.parentNode
for node in by_direction[dimension]:
print node.parentNode
from xml.dom import minidom
xmldoc = minidom.parse("C:/Users/Dsduda/Desktop/Countries.xml")
x = xmldoc.getElementsByTagName("neighbor")
y = xmldoc.getElementsByTagName("neighbor")
for s in x and t in y:
if s.attributes["direction"].value == t.attributes["dimension"].value:
print s.parentNode, t.parentNode
from collections import defaultdict
by_direction = defaultdict(list)
# map directions
for neighbor in xmldoc.getElementsByTagName("neighbor"):
if not 'direction' in neighbor.attributes:
continue
direction = neighor.attributes['direction'].value
by_direction[direction].append(neighbor)
# look up by dimension:
for neighbor in xmldoc.getElementsByTagName("neighbor"):
if not 'dimension' in neighbor.attributes:
continue
dimension = neighor.attributes['dimension'].value
print neighbor.parentNode
for node in by_direction[dimension]:
print node.parentNode