Add xml node to xml file using python

I wonder if itโ€™s better to add an element while opening a file, look for a โ€œgood placeโ€ and add a line containing xml code. Or use the library ... I have no idea. I know how I can get nodes and properties from xml via, for example, lxml, but what is the easiest and best way to add?

+4
source share
2 answers

You can use lxml.etree.Element to create xml node (s), and use append or insert to attach them to an XML document:

data='''\ <root> <node1> <node2 a1="x1"> ... </node2> <node2 a1="x2"> ... </node2> <node2 a1="x1"> ... </node2> </node1> </root> ''' doc = lxml.etree.XML(data) e=doc.find('node1') child = lxml.etree.Element("node3",attrib={'a1':'x3'}) child.text='...' e.insert(1,child) print(lxml.etree.tostring(doc)) 

gives:

 <root> <node1> <node2 a1="x1"> ... </node2> <node3 a1="x3">...</node3><node2 a1="x2"> ... </node2> <node2 a1="x1"> ... </node2> </node1> </root> 
+4
source

The safest way to add nodes to an XML document is to load it into the DOM, add nodes programmatically, and write it again. There are several Python XML libraries. I used mini-humor, but I have no reason to recommend it specifically over others.

+1
source

Source: https://habr.com/ru/post/1311912/


All Articles