XML 用 XMLtree 或 MINIDOM 解析
XML parsing with XMLtree or MINIDOM
我有一个 xml 文件,在它的中间有一个这样的块:
...
<node id = "1" >
<ngh id = "2" > 100 </ngh>
<ngh id = "3"> 300 </ngh>
</node>
<node id = "2">
<ngh id = "1" > 400 </ngh>
<ngh id = "3"> 500 </ngh>
</node>
...
并试图获得
1, 2, 100
1, 3, 300
2, 1, 400
2, 3, 500
...
我发现了一个类似的问题并做了以下操作
from xml.dom import minidom
xmldoc = minidom.parse('file.xml')
nodelist = xmldoc.getElementsByTagName('node')
for s in nodelist:
print s.attributes['id'].value)
有没有办法让我得到标签之间的值(即 100、300、400)?
您需要对 ngh
个元素进行内部循环:
from xml.dom import minidom
xmldoc = minidom.parse('file.xml')
nodes = xmldoc.getElementsByTagName('node')
for node in nodes:
node_id = node.attributes['id'].value
for ngh in node.getElementsByTagName('ngh'):
ngh_id = ngh.attributes['id'].value
ngh_text = ngh.firstChild.nodeValue
print node_id, ngh_id, ngh_text
打印:
1 2 100
1 3 300
2 1 400
2 3 500
我有一个 xml 文件,在它的中间有一个这样的块:
...
<node id = "1" >
<ngh id = "2" > 100 </ngh>
<ngh id = "3"> 300 </ngh>
</node>
<node id = "2">
<ngh id = "1" > 400 </ngh>
<ngh id = "3"> 500 </ngh>
</node>
...
并试图获得
1, 2, 100
1, 3, 300
2, 1, 400
2, 3, 500
...
我发现了一个类似的问题并做了以下操作
from xml.dom import minidom
xmldoc = minidom.parse('file.xml')
nodelist = xmldoc.getElementsByTagName('node')
for s in nodelist:
print s.attributes['id'].value)
有没有办法让我得到标签之间的值(即 100、300、400)?
您需要对 ngh
个元素进行内部循环:
from xml.dom import minidom
xmldoc = minidom.parse('file.xml')
nodes = xmldoc.getElementsByTagName('node')
for node in nodes:
node_id = node.attributes['id'].value
for ngh in node.getElementsByTagName('ngh'):
ngh_id = ngh.attributes['id'].value
ngh_text = ngh.firstChild.nodeValue
print node_id, ngh_id, ngh_text
打印:
1 2 100
1 3 300
2 1 400
2 3 500