python - 使用 XMLtree 或 MINIDOM 进行 XML 解析

标签 python xml xml-parsing minidom

我有一个 xml 文件,在它的中间有一个像这样的 block :

...
<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

关于python - 使用 XMLtree 或 MINIDOM 进行 XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28822925/

相关文章:

Python:将字典列表转换为列表列表

mysql - MySQL 没有的 XML 的实际用途是什么?

java - 如何使用节点名称和特定属性值获取节点及其子节点?

java - 如何获取 xml 中父标签内标签名称及其值的数据

python - 端口已被使用

python - 获取 STDOUT、STDERR 而不等待进程退出

python - anchor 元素的 XPath 不在某些父元素中?

java - UTF-8 到 UTF16 解析

python - 从网页中抓取 pdf

xml - 如何从带有命名空间的 XML 中获取 'select'?