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')
Share:
10,936

Related videos on Youtube

user2136786
Author by

user2136786

Updated on October 14, 2022

Comments

  • user2136786
    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 with new_entry tree and save the file.

  • shubham12511
    shubham12511 over 5 years
    pretty_print=True is not working for appended nodes.
  • Salvatore
    Salvatore about 5 years
    The last part of this code is not working for me. etree.tostring() returns bytes and so f.write() throws the following exception: TypeError, write() argument must be str, not bytes. I suggest to either convert bytes to string adding .decode("utf-8") at the end of etree.tostring(root, pretty_print=True), or use the ElementTree.write() method in this way tree.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
    pt1 almost 3 years
    The 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
    ccpizza over 1 year
    @Salvatore: you can use etree.tostring(root, pretty_print=True, encoding=str)