XML Python can this be improved ok spent ages on this simple problem (I'm not good at XML) below code is probably self explanatory and it works, but i think this could be done a lot easier

Sample XML

&lt;data&gt;
        &lt;id name="ch01"&gt;
                &lt;channel&gt;test channel 1&lt;/channel&gt;
                &lt;gpio&gt;3&lt;/gpio&gt;
                &lt;cont&gt;front&lt;/cont&gt;
        &lt;/id&gt;

        &lt;id name="ch02"&gt;
                &lt;channel&gt;test channel 2&lt;/channel&gt;
                &lt;gpio&gt;5&lt;/gpio&gt;
                &lt;cont&gt;back&lt;/cont&gt;
        &lt;/id&gt;
&lt;/data&gt;


The code used, which I eventually got working after reading a few posts on here:

from xml.dom import minidom
dom = minidom.parse('/usr/local/sbin/logger/chaninfo_test.xml')
id=dom.getElementsByTagName('id')
for node in id:
        chanid=node.getAttribute('name')
        print chanid
        clist=node.getElementsByTagName('channel')
        for c in clist:
                print c.childNodes[0].nodeValue

        glist=node.getElementsByTagName('gpio')
        for g in glist:
                print g.childNodes[0].nodeValue

        colist=node.getElementsByTagName('cont')
        for co in colist:
                print co.childNodes[0].nodeValue
        print


Can this be improved or cleaned up? The XML will increase in size but contents won't change, multiple IDs with one channel, gpis and cont field each.

The first thing that I'm thinking about is combining is and name is channel id='name', etc.
Use for in loops to avoid repetition

These 3 blocks of code are very similar:

1

    clist=node.getElementsByTagName('channel')
    for c in clist:
            print c.childNodes[0].nodeValue


2

    glist=node.getElementsByTagName('gpio')
    for g in glist:
            print g.childNodes[0].nodeValue


3

    colist=node.getElementsByTagName('cont')
    for co in colist:
            print co.childNodes[0].nodeValue




We can clean up by abstracting what is different (the name) into a loop variable:

for name in ('channel', 'gpio', 'cont'):
    for element in node.getElementsByTagName(name):
        print element.childNodes[0].nodeValue


Now also adding another name will lead to only adding it to the list instead of repeating similar code the fourth time.