【问题标题】:XML parsing with XMLtree or MINIDOM使用 XMLtree 或 MINIDOM 进行 XML 解析
【发布时间】:2015-03-03 02:09:36
【问题描述】:

我有一个 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)?

【问题讨论】:

    标签: python xml xml-parsing minidom


    【解决方案1】:

    您需要对 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      相关资源
      最近更新 更多