Problem inserting an element where I want it using lxml
Josh English
Joshua.R.English at gmail.com
Wed Jan 5 01:16:14 EST 2011
Here's a trimmed down version of how I did this (using ElementTree standalone, but the API should be the same)
This is from a class definition and the _elem attribute is a link to an ElementTree.Element object.
...
def _add_elem(self, tagName, text, attrib ={}):
"""_add_elem(tagName, text, attrib={})
Adds a child element in the appropriate place in the tree.
Raises an IndexError if the checker does not allow an addition child of tagName.
"""
last_child = None
for child in self._elem.findall('.//%s' % tagName):
last_child = child
if last_child is None:
new_child = ET.SubElement(self._elem, tagName, attrib)
else:
new_child = ET.Element(tagName, attrib)
self._elem.insert(self._elem._children.index(last_child)+1, new_child)
new_child.text=str(text)
return new_child
I don't think you need to count the instances of the bingo node (unless you want to prevent too many from being added in).
Josh
More information about the Python-list
mailing list