[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.