XML - attributes query

Piet van Oostrum piet at cs.uu.nl
Sat Mar 1 17:29:58 CET 2003

>>>>> "Newt" <newt_e at blueyonder.co.uk> (N) wrote:

N> Hi all,
N> I'm trying to use the following code fragment tp pick up some attributes
N> from an XML element.

N> doc = xml.dom.minidom.parse("gard_skills_ele.xml")

N> for s in doc.getElementsByTagName("skill"):
N>     print s.childNodes.length
N>     for c in s.childNodes:
N>         print "--> " + c.nodeName
N>     print "--> Has " + str(s.attributes.length) + " attributes"
N>     print str(s.attributes.getNamedItem("name"))

N> The xml input file looks like:

N> <xml>
N> <skill name="Art" points="1" />
N> <skill name="Calligraphy" points="1" />
N> <skill name="Ettiquette" points="1" />
N> </xml>

N> When I run the code, I get the following error:

N> Traceback (most recent call last):
N>   File "D:\py_stuff\test_xml.py", line 22, in ?
N>     print str(s.attributes.getNamedItem("name"))
N> AttributeError: NamedNodeMap instance has no attribute 'getNamedItem'

N> The book I'm using (Python and XML) says that NamedNodeMap does support
N> getNamedItem.
N> Has anyone tried to use this?

Your examples works with Python 2.2 and 2.3a2.

--> Has 2 attributes
<xml.dom.minidom.Attr instance at 0x35f360>
--> Has 2 attributes
<xml.dom.minidom.Attr instance at 0x35ff70>
--> Has 2 attributes
<xml.dom.minidom.Attr instance at 0x360af0>

With the last line changed into:
    print str(s.attributes.getNamedItem("name").nodeValue)

--> Has 2 attributes
--> Has 2 attributes
--> Has 2 attributes
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl

More information about the Python-list mailing list