如何使用lxml更新XML文件 [英] How to update XML file with lxml
本文介绍了如何使用lxml更新XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过使用lxml库用新信息更新xml文件. 例如,我有以下代码:
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')
其中的"books.xml"文件具有以下内容: http://www.w3schools. com/dom/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>''')
我的问题是,如何用new_entry
树更新tree
元素树并保存文件.
My question is, how can I update tree
element tree with new_entry
tree and save the file.
推荐答案
在这里,获取树的根,追加新元素,将树作为字符串保存到文件中
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()
这篇关于如何使用lxml更新XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文