How to update XML file with lxml
10,936
Solution 1
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()
Solution 2
I don't have enough reputation to comment, therefore I'll write an answer...
The most simple change make the code of Guillaume work is to change the line
f = open('books-mod.xml', 'w')
to
f = open('books-mod.xml', 'wb')
Related videos on Youtube
Author by
user2136786
Updated on October 14, 2022Comments
-
user2136786 about 1 year
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 withnew_entry
tree and save the file. -
shubham12511 over 5 yearspretty_print=True is not working for appended nodes.
-
Salvatore about 5 yearsThe last part of this code is not working for me.
etree.tostring()
returnsbytes
and sof.write()
throws the following exception:TypeError, write() argument must be str, not bytes
. I suggest to either convertbytes
tostring
adding.decode("utf-8")
at the end ofetree.tostring(root, pretty_print=True)
, or use theElementTree.write()
method in this waytree.write("new/file/path")
. While the first snippet updates an existing file, while te second one creates a new file, but both can be used for the purpose of this question. -
pt1 almost 3 yearsThe most simple change make the code work is to change the line f = open('books-mod.xml', 'w') to f = open('books-mod.xml', 'wb')
-
ccpizza over 1 year@Salvatore: you can use
etree.tostring(root, pretty_print=True, encoding=str)