How to update XML file using lxml

I want to update an xml file using the new lxml library. For example, I have this code:

>>> from lxml import etree >>> >>> tree = etree.parse('books.xml') 

where the books.xml file is located, has this content: http://www.w3schools.com/dom/books.xml

I want to update this file with a new book:

 >>> new_entry = etree.fromstring('''<book category="web" cover="paperback"> ... <title lang="en">Learning XML 2</title> ... <author>Erik Ray</author> ... <year>2006</year> ... <price>49.95</price> ... </book>''') 

My question is how can I update the tree of tree elements using the new_entry tree and save the file.

+7
source share
1 answer

Here you go, get the root of the tree, add a new element, save the tree as a string in a file:

 from lxml import etree tree = etree.parse('books.xml') new_entry = etree.fromstring('''<book category="web" cover="paperback"> <title lang="en">Learning XML 2</title> <author>Erik Ray</author> <year>2006</year> <price>49.95</price> </book>''') root = tree.getroot() root.append(new_entry) f = open('books-mod.xml', 'w') f.write(etree.tostring(root, pretty_print=True)) f.close() 
+8
source

All Articles