Skip to content Skip to sidebar Skip to footer

Lxml: Insert Tag At A Given Position

I have an xml file, similar to this: text1 parser = etree.XMLParser(remove_blank_text=True) tag = etree.fromstring(XML, parser) subtag1 = tag.find("subtag1") subtag2 = etree.Element("subtag2", subattrib2="2") subtext = etree.SubElement(subtag2, "subtext") subtext.text = "text2" subtag1.addnext(subtag2) # Add subtag2 as a following sibling of subtag1print etree.tostring(tag, pretty_print=True)

Output:

<tagattrib1="I"><subtag1subattrib1="1"><subtext>text1</subtext></subtag1><subtag2subattrib2="2"><subtext>text2</subtext></subtag2><subtag3subattrib3="3"><subtext>text3</subtext></subtag3></tag>

Alternative: use insert() on the root element:

subtag2 = etree.Element("subtag2", subattrib2="2")
subtext = etree.SubElement(subtag2, "subtext")
subtext.text = "text2"
tag.insert(1, subtag2)   # Add subtag2 as the second child (index 1) of the root element

Post a Comment for "Lxml: Insert Tag At A Given Position"