views:

86

answers:

1

In the following code below, how to retrieve the value of id,Id has multiple values in it.How to access the values of id and update it to result1

def parse_results ():

     try:
        xml = minidom.parseString(new_results)
        for xmlchild in xmldoc.childNodes[0].childNodes :
           result1 = {}
           result1.update ({'firstname': xmlchild.getElementsByTagName("firstname")[0].childNodes[0].nodeValue})
           result1.update ({'lastname': xmlchild.getElementsByTagName("lastname")[0].childNodes[0].nodeValue})
           result1.update ({'address': address})
           if xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue:     
              logging.debug(xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue.lower())        

           result1.update ({'id': id})

Edit:

xmlchild.getElementsByTagName("id")[0].childNodes[0].nodeValue -this statement gives an exception

Adding XML:

 <info><firstname>firstname</firstname><lastname>lastname</lastname><id>2</id></info>
 <info><firstname>firstname</firstname><lastname>lastname</lastname><id>3</id></info>
 <info><firstname>firstname</firstname><lastname>lastname</lastname><id>4</id></info>
A: 

Why are you using minidom? It is really boring to use.

I suggest you move to element tree:

import xml.etree.ElementTree as et
d = et.fromstring('''
<doc>
 <info><firstname>firstname</firstname><lastname>lastname</lastname><id>2</id></info>
 <info><firstname>firstname</firstname><lastname>lastname</lastname><id>3</id></info>
 <info><firstname>firstname</firstname><lastname>lastname</lastname><id>4</id></info>
</doc>
''')

result = [dict((el.tag, el.text) for el in info) for info in d.findall('info')]
print result

That prints:

[{'firstname': 'firstname', 'id': '2', 'lastname': 'lastname'},
 {'firstname': 'firstname', 'id': '3', 'lastname': 'lastname'},
 {'firstname': 'firstname', 'id': '4', 'lastname': 'lastname'}]
nosklo
Element Tree isn't part of the default install, is it? That's probably why. The OP would need to install lxml (http://codespeak.net/lxml/). Other than that, I agree completely. Way easier to use.
Tom
@Tom: Luckly, it is part of the default install, since python 2.5: http://docs.python.org/library/xml.etree.elementtree.html - I've added the link to my answer.
nosklo
@Tom: Installing lxml is still worth it for the extra xpath support, though, which is really nice.
nosklo
Strange. Maybe it's us poor Windows folks-- I have Python 2.5 and when I wanted to use that xpath support, I had to install the library. Either way, I'm happy to know it's there as part of the default nowadays.
Tom
@Tom: xpath support is lxml-only - but I'm not using it. The code in my answer uses `.findall()` only.
nosklo