Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update XML file with lxml

Tags:

python

xml

lxml

I want to update xml file with new information by using lxml library. For example, I have this code:

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

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

I want to update this file with 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 tree element tree with new_entry tree and save the file.

like image 543
user2136786 Avatar asked Jun 21 '13 22:06

user2136786


People also ask

Is XML and lxml are same?

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers.


1 Answers

Here you go, get the root of the tree, append your new element, save the tree as a string to 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', 'wb')
f.write(etree.tostring(root, pretty_print=True))
f.close()
like image 63
Guillaume Avatar answered Oct 16 '22 10:10

Guillaume