Skip to content

Instantly share code, notes, and snippets.

@kyamagu
Last active February 4, 2019 08:39
Show Gist options
  • Save kyamagu/1e4b82ba091a960390e3b934d33b5de3 to your computer and use it in GitHub Desktop.
Save kyamagu/1e4b82ba091a960390e3b934d33b5de3 to your computer and use it in GitHub Desktop.
Customized ETree element
import io
import xml.etree.ElementTree as ET
class BaseElement(ET.Element):
def __init__(self, tag, attrib={}, **extra):
super(BaseElement, self).__init__(tag, attrib=attrib, **extra)
self._parent = None
@property
def parent(self):
return self._parent if hasattr(self, '_parent') else None
def __setitem__(self, index, element):
super(BaseElement, self).__setitem__(index, element)
element._parent = self
def __delitem__(self, index):
self._children[index]._parent = None
del self._children[index]
def append(self, element):
super(BaseElement, self).append(element)
element._parent = self
def extend(self, elements):
super(BaseElement, self).extend(element)
for element in elements:
element._parent = self
def insert(self, index, element):
super(BaseElement, self).insert(index, element)
element._parent = self
def remove(self, element):
element._parent = None
super(BaseElement, self).remove(element)
def clear(self):
for element in self:
element._parent = None
super(BaseElement, self).clear()
value = r"""
<body>
<p>hello</p>
<p>world</p>
<ul><li>thanks</li></ul>
</body>
"""
parser = ET.XMLParser(target=ET.TreeBuilder(element_factory=BaseElement))
tree = ET.parse(io.StringIO(value), parser=parser)
root = tree.getroot()
print(root[0])
print(root[0].parent)
@kyamagu
Copy link
Author

kyamagu commented Feb 4, 2019

lxml has getparent() method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment