[XML-SIG] enumerate the attributes?

Martin v. Loewis martin@loewis.home.cs.tu-berlin.de
Thu, 6 Sep 2001 22:39:46 +0200


> Hi, is there a way to enumerate the attributes of a node?

Certainly. The .attributes property of a Node is of type NamedNodeMap,
see

http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-84CF096

The NamedNodeMap, in turn, has a .length attribute, and a .item()
method, see

http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1780488922

So with pure DOM only, you get

    # something like this:
    for aindex in range(foo.attributes.length):
        a = foo.attributes.item(aindex)  
        print "%s = %s" % (a.name, a.value)

> 	# ideally, attributes would be a dictionary too:
> 	a = "id"
> 	print "%s = %s" % (a, foo.attributes[a])

As documented in

http://www.python.org/doc/current/lib/dom-attributelist-objects.html

there is an experimental API for NamedNodeMaps to treat them as
dictionaries. This works in many case, like the one you mention.
It also allows you to write

for a in foo.attributes.values():
    print "%s = %s" % (a.name, a.value)

> 	# something like this:
> 	for a in foo.attributes:
> 		print "%s = %s" % (a.name, a.value)

Iterating over a NamedNodeMap itself is an extension that is only
available in 4DOM. The tricky part is that foo.attributes['id'] ought
to operate dictionary-like, whereas foo.attributes[0] ought to operate
sequence-like. Guido once commented to that API

<quote>

Aaaaaaargh!!!!!!!

You mean somebody wrote a subclass of UserDict that attempts
to behave like a sequence by checking the type of the
__getitem__ argument??????????

Yuck!!!!!!!!!!!!!!!

You XML weenies are sickos. :-)
</quote>

I guess you won't see this extension in minidom :-)

Regards,
Martin