Need help with basic DOM XML tree traversing

Stefan Behnel stefan_ml at behnel.de
Sun Apr 25 11:41:57 EDT 2010


Barak, Ron, 25.04.2010 17:06:
> This is my first try at XML with Python, and though I tried to read on the web, I'm unable to traverse a DOM tree, as my top element seems to be DOCUMENT_NODE and I cannot find a way to get to the nodes below it.

You might find the xml.etree.ElementTree package a lot easier to work with.


> $ python -u xml_parse.py
> node:<xml.dom.minidom.DocumentType instance at 0x00DE25A8>
> dom2.nodeType: 9
> dom2.nodeName: #document
> node is DOCUMENT_NODE:<xml.dom.minidom.DocumentType instance at 0x00DE25A8>
> node:<DOM Element: database at 0xde2698>
> dom2.nodeType: 9
> dom2.nodeName: #document
> node is DOCUMENT_NODE:<DOM Element: database at 0xde2698>
> ('dom2._get_childNodes():', [<xml.dom.minidom.DocumentType instance at 0x00DE25A8>,<DOM Element: database at 0xde2698>])
> Traceback (most recent call last):
>    File "xml_parse.py", line 26, in<module>
>      print("child_nodes._get_childNodes():",child_nodes._get_childNodes())
> AttributeError: 'NodeList' object has no attribute '_get_childNodes'

"childNodes" is a property, use it like

     print("child_nodes.childNodes:", child_nodes.childNodes)

By convention, the underscore at the beginning of "_get_childNodes" 
indicates that it is not considered a public method.

Stefan




More information about the Python-list mailing list