Problem inserting an element where I want it using lxml

Alan Meyer ameyer2 at yahoo.com
Wed Jan 5 06:25:11 EST 2011


On 01/05/2011 01:16 AM, Josh English wrote:
> 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

Thanks Josh.  It looks like lxml adds some incredibly useful extensions
to ElementTree that I will use.  See Stephan's reply.

     Alan



More information about the Python-list mailing list