Emmet B
Emmet B

Reputation: 5541

XML parsing with XMLtree or MINIDOM

I have a xml file, and in the middle of it I have a block like this:

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

and trying to get

1, 2, 100
1, 3, 300
2, 1, 400
2, 3, 500
...

I found a similar question and did the following

from xml.dom import minidom
xmldoc = minidom.parse('file.xml')
nodelist = xmldoc.getElementsByTagName('node')

for s in nodelist:
    print s.attributes['id'].value)

is there a way to get i get the values between tags (i.e. 100, 300, 400) ?

Upvotes: 1

Views: 72

Answers (1)

alecxe
alecxe

Reputation: 474003

You need an inner loop over ngh elements:

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

Prints:

1 2 100
1 3 300
2 1 400
2 3 500

Upvotes: 3

Related Questions