Trying to parse an XML file with Python - what am I doing wrong?
Question: I'm working with XML and Python for the first time. The ultimate goal is to
send a request to a REST service, receive a response in XML, and parse the
values and send emails depending on what was returned. However, the REST
service is not yet in place, so for now I'm experimenting with an XML file
saved on my C drive.

I have a simple bit of code, and I'm confused about why it isn't working.

This is my xml file ("XMLTest.xml"):

    
    
    <Response>
        <exitCode>1</exitCode>
        <fileName>C:/Something/</fileName>
        <errors>
            <error>Error generating report</error>
        </errors>
    </Response>
    

This is my code so far:

    
    
    from xml.dom import minidom
    
    something = open("C:/XMLTest.xml")
    something = minidom.parse(something)
    
    nodeList = []
    for node in something.getElementsByTagName("Response"):  
        nodeList.extend(t.nodeValue for t in node.childNodes)
    print nodeList
    

But the results that print out are...

    
    
    [u'\n\t', None, u'\n\t', None, u'\n\t', None, u'\n']
    

What am I doing wrong?

I'm trying to get the node values. Is there a better way to do this? Is there
a built-in method in Python to convert an xml file to an object or dictionary?
I'd like to get all the values, preferably with the names attached.


Answer: Does this help?

    
    
    doc = '''<Response>
        <exitCode>1</exitCode>
        <fileName>C:/Something/</fileName>
        <errors>
            <error>Error generating report</error>
        </errors>
    </Response>'''
    
    from xml.dom import minidom
    
    something = minidom.parseString( doc )
    
    nodeList = [ ]
    for node in something.getElementsByTagName( "Response" ):
        response = { }
        response[ "exit code" ] = node.getElementsByTagName( "exitCode" )[ 0 ].childNodes[ 0 ].nodeValue
        response[ "file name" ] = node.getElementsByTagName( "fileName" )[ 0 ].childNodes[ 0 ].nodeValue
        errors = node.getElementsByTagName( "errors" )[ 0 ].getElementsByTagName( "error" )
        response[ "errors" ] = [ error.childNodes[ 0 ].nodeValue for error in errors ]
    
        nodeList.append( response )
    
    import pprint
    pprint.pprint( nodeList )
    

yields

    
    
    [{'errors': [u'Error generating report'],
      'exit code': u'1',
      'file name': u'C:/Something/'}]
    

