I'd like to parse an xml document using Python's xml.etree.ElementTree module. However, I want all the elements in the resulting tree object to have some class methods that I define. This suggests creating my own subclass of Python's element class, but I'm having trouble telling the parser to use my own element subclass when parsing, instead of the built in class.
For example, let's say I want the nodes in the tree to have a new method called custommethod(). To do this, I create an element subclass:
class MyElement(xml.etree.ElementTree._Element):
def custommethod():
. . .
Now, when I parse a tree using
tree = xml.etree.ElementTree.parse(source)
I want all the elements in tree to have the custommethod() method. So,
tree.getroot.custommethod()
should not fail.
But I don't know how to tell the parser to use my element class - is this even possible? There are some hints in the Python documentation about passing a custom parser to .parse(), but not a lot of details.