Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Minidom - how to iterate through attributes, and get their name and value

I want to iterate through all attributes of a dom node and get the name and value

I tried something like this (docs were not very verbose on this so I guessed a little):

for attr in element.attributes:
    attrName = attr.name
    attrValue = attr.value
  1. the for loop doesn't even start
  2. how do I get the name and value of the attribute once I get the loop to work?

Loop Error:

for attr in element.attributes:
  File "C:\Python32\lib\xml\dom\minidom.py", line 553, in __getitem__
    return self._attrs[attname_or_tuple]
 KeyError: 0

I'm new to Python, be gentle please

like image 475
Eran Medan Avatar asked Jul 25 '12 16:07

Eran Medan


People also ask

Is there a DOM in Python?

The DOM is a standard tree representation for XML data. The Document Object Model is being defined by the W3C in stages, or “levels” in their terminology. The Python mapping of the API is substantially based on the DOM Level 2 recommendation. DOM applications typically start by parsing some XML into a DOM.

What is Toprettyxml?

toprettyxml. n.toprettyxml(indent='\t',newl='\n') Returns a string, plain or Unicode, with the XML source for the subtree rooted at n, using indent to indent nested tags and newl to end lines. toxml. n.toxml( )

What is XML DOM. minidom?

xml. dom. minidom is a minimal implementation of the Document Object Model interface, with an API similar to that in other languages. It is intended to be simpler than the full DOM and also significantly smaller.


1 Answers

There is a short and efficient (and pythonic ?) way to do it easily

#since items() is a tUple list, you can go as follows :
for attrName, attrValue in element.attributes.items():
    #do whatever you'd like
    print "attribute %s = %s" % (attrName, attrValue)

If what you are trying to achieve is to transfer those inconvenient attribute NamedNodeMap to a more usable dictionary you can proceed as follows

#remember items() is a tUple list :
myDict = dict(element.attributes.items())

see http://docs.python.org/2/library/stdtypes.html#mapping-types-dict and more precisely example :

d = dict([('two', 2), ('one', 1), ('three', 3)])
like image 114
Ar3s Avatar answered Sep 22 '22 15:09

Ar3s