Created
March 5, 2013 15:01
-
-
Save anonymous/5090902 to your computer and use it in GitHub Desktop.
Sometimes it is helpful for ElementrTree elements to reference their parent. This monkey patches ElementTree, but does not work with cElementTree. Found this going through some old filed (dated 2008-12-18) and figured it was worth saving.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from xml.etree import ElementTree as etree | |
class _ElementInterface(etree._ElementInterface): | |
""" Add a 'parent' property to ElementTree Elements. Defaults to None. """ | |
parent = None | |
etree._ElementInterface = _ElementInterface | |
def SubElement(parent, tag, attrib={}, **extra): | |
""" Replace SubElement factory func with one that also sets an Element's parent. """ | |
attrib = attrib.copy() | |
attrib.update(extra) | |
element = parent.makeelement(tag, attrib) | |
parent.append(element) | |
element.parent = parent | |
return element | |
etree.SubElement = SubElement |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment