trouble with minidom

Ronn Ross ronn.ross at gmail.com
Fri Jul 24 13:56:29 EDT 2009


On Tue, Jul 21, 2009 at 7:32 PM, Gabriel Genellina
<gagsl-py2 at yahoo.com.ar>wrote:

> En Tue, 21 Jul 2009 21:08:57 -0300, Ronn Ross <ronn.ross at gmail.com>
> escribió:
>
>
>  Hello I'm trying to read an xml file using minidome. The xml looks like:
>> <rootNode>
>>   <project>
>>      <name>myProj</name>
>>      <path>/here/</path>
>>   </project>
>> </rootNode>
>>
>> My code looks like so:
>> from xml.dom.minidom import parse
>>
>> dom = parse("myfile.xml")
>>
>> for node in dom.getElementsByTagName("project'):
>>   print('name: %s, path: %s \n') % (node.childNodes[0].nodeValue,
>> node.childNodes[1])
>>
>> Unfortunately, it returns 'nodeValue as none. I'm trying to read the value
>> out of the node fir example name: myProj. I haven't found much help in the
>> documentation. Can someone point me in the right direction?
>>
>
> Unless you have a specific reason to use the DOM interface (like having a
> masochistic mind), working with ElementTree usually is a lot easier:
>
> py> import xml.etree.ElementTree as ET
> py> xml = """<rootNode>
> ... <project>
> ...        <name>myProj</name>
> ...        <path>/here/</path>
> ... </project>
> ... </rootNode>"""
> py> doc = ET.fromstring(xml)
> py> for project in doc.findall('project'):
> ...   for child in project.getchildren():
> ...     print child.tag, child.text
> ...
> name myProj
> path /here/
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


I have used the loop below and it works great, but I need get both child
elements or 'project' per iteration. I want to build a dictionary that
resemble this:
my_dict = {'myProj':'/here/', 'anothername':'anotherpath'}

I couldn't find how to do with in the element tree docs. Can you point me in
the right direction?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090724/043fd697/attachment-0001.html>


More information about the Python-list mailing list