Skip to content

Instantly share code, notes, and snippets.

Created March 5, 2013 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/5090902 to your computer and use it in GitHub Desktop.
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.
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