Python minidom: list childnode attributes per parent tag

user1552586 picture user1552586 · Aug 2, 2012 · Viewed 9.4k times · Source

I have,

<parent id="1">
    <child id="white"></child>
    <child id="red"></child>
</parent>
<parent id="2">
    <child id="green"></child>
    <child id="gray"></child>
</parent>

I need this output,

1 
 white
 red
2
 green
 gray

This is how I am doing it,

parent = xmldoc.getElementsByTagName('parent')
for item in parent:
    child = xmldoc.getElementsByTagName('child')
    child_id = child.getAttribute('id')
    for child_id in child:
        print child_id

Of course, I'm getting it wrong, but do not know how to loop through these parent ids and collect each list individually. I would appreciate some help!

Answer

Thai Tran picture Thai Tran · Aug 2, 2012

Try this

import xml.dom.minidom as minidom

a = '<parent id="1"><child id="white"></child><child id="red"></child></parent>'
dom = minidom.parseString(a)

for parent in dom.childNodes:
    print parent.getAttribute('id')
    for child in parent.childNodes:
        print '  %s' % child.getAttribute('id')