How to update XML file with lxml

痴心易碎 提交于 2020-01-11 04:53:06

问题


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.


回答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', 'w')
f.write(etree.tostring(root, pretty_print=True))
f.close()



回答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')


来源:https://stackoverflow.com/questions/17245310/how-to-update-xml-file-with-lxml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!