Search code examples
insertpositionlxmlelement

insert child element at last position


Given a parent element, how do I insert a child element at the last position? So far, using an index of -1 places the child at the penultimate position:

In [22]: et.tostring(test)
Out[22]: b'<a><orange/><b>hee</b><apple/><pear/><b>haa</b></a>'
In [23]: test.insert(-1, et.Element('mango'))
In [24]: et.tostring(test)
Out[24]: b'<a><orange/><b>hee</b><apple/><pear/><mango/><b>haa</b></a>'

Solution

  • Get the number of child elements (with len()) and use that as the index.

    from lxml import etree as et
    
    test = et.fromstring('<a><orange/><b>hee</b><apple/><pear/><b>haa</b></a>')
    test.insert(len(test), et.Element('mango')) 
    print et.tostring(test, pretty_print=True)
    

    Output:

    <a>
      <orange/>
      <b>hee</b>
      <apple/>
      <pear/>
      <b>haa</b>
      <mango/>
    </a>