I want to add an element to an xml-file at a specific path whose subnodes do not exist in the initial example.xml file. When adding the element, I want to create all the necessary child nodes "on the fly" and not one at a time.
I don't know the correct way to do it, the following code-snipped is just an example for illustration purposes. Maybe it is possible using different methods from etree.
My example:
from lxml import etree
tree = etree.parse('example.xml')
root = tree.getroot()
path = etree.Element('/leadSinger/names/firstName')
etree.Element(path, "Freddie")
tree.write('example.xml')
The initial example.xml file:
<interpret>
<name>Queen</name>
<interpret>
The example.xml file after the element was created, inserted and written:
<interpret>
<name>Queen</name>
<leadSinger>
<names>
<firstName>Freddie</firstName>
</names>
</leadSinger>
</interpret>
CodePudding user response:
You can try it this way:
lead = """<leadSinger>
<names>
<firstName>Freddie</firstName>
</names>
</leadSinger>
"""
elem = etree.fromstring(lead)
destination = root.xpath('//interpret/name')[0]
destination.addnext(elem)
print(etree.tostring(root, encoding="unicode", pretty_print=True))
Which should get you the expected output.