Next / Previous / Contents / TCC Help System / NM Tech homepage

9.12. Element.insert(): Insert a new child element

Use the .insert() method on an Element instance E to add a new element child elt in an arbitrary position. (To append a new element child at the last position, see Section 9.3, “Element.append(): Add a new element child”.)

E.insert(index, elt)

The index argument specifies the position into which element elt is inserted. For example, if you specify index 0, the new child will be inserted before any other children of E.

The lxml module is quite permissive about the values of the index argument: if it is negative, or greater than the position of the last existing child, the new child is added after all existing children.

Here is an example showing insertions at positions 0 and 2.

>>> node = etree.fromstring('<a><c0/><c1/><c2/></a>')
>>> newKid = etree.Element('c-1', laugh="Hi!")
>>> node.insert(0, newKid)
>>> etree.tostring(node)
'<a><c-1 laugh="Hi!"/><c0/><c1/><c2/></a>'
>>> newerKid = etree.Element('cn')
>>> node.insert(2, newerKid)
>>> etree.tostring(node)
'<a><c-1 laugh="Hi!"/><c0/><cn/><c1/><c2/></a>'
>>>