I'm using minidom to parse XML and to simplify accessing child nodes, I'm trying to implement __getattr__ for the Node class. Yes, I know what most of you will think of that; I'll just have to be careful, won't I. ;)
outputs:
As far as I can tell, everything works fine, except __getattr__ never gets called. Can anyone help me understand why that is or how to work around it?
Code:
import xml
from xml.dom.minidom import parseString
def getChild(self, name):
print "Getting child"
return self.getElementsByTagName(name)[0]
xml.dom.minidom.Node.__getattr__ = getChild
xmlDoc = parseString('''<?xml version="1.0" encoding="ISO-8859-1"?>
<CATALOG>
<cd>
<title>Empire Burlesque</title>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</cd>
<cd>
<title>Hide your heart</title>
<ARTIST>Bonnie Tylor</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</cd>
</CATALOG>''')
xmlRoot = xmlDoc.childNodes[0]
print xmlRoot.__getattr__
print xmlRoot.cd.title.childNodes[0].nodeValue
Code:
<bound method Element.getChild of <DOM Element: CATALOG at 0x1c50850>>
File "C:\Users\Tuomas\Projektit\wrestlevania\ezXML.py", line 31, in <module>
print xmlRoot.cd.title.childNodes[0].nodeValue
AttributeError: Element instance has no attribute 'cd'
Comment