我想使用lxml库更新包含新信息的xml文件.
例如,我有这个代码:
>>> from lxml import etree
>>>
>>> tree = etree.parse('books.xml')
其中’books.xml’文件,其内容为:http://www.w3schools.com/dom/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>''')
我的问题是,如何用new_entry树更新树元素树并保存文件.
解决方法:
在这里,获取树的根,附加新元素,将树作为字符串保存到文件中:
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()