使用Python中的lxml库编写xml文件

时间:2010-05-14 09:48:58

标签: python xml lxml

我正在使用lxml从头开始创建XML文件; 有这样的代码:

from lxml import etree

root = etree.Element("root")
root.set("interesting", "somewhat")
child1 = etree.SubElement(root, "test")

如何使用Element类的write()方法将根ElementTree对象写入xml文件?

5 个答案:

答案 0 :(得分:54)

您可以从元素中获取字符串,然后从lxml tutorial

中写出
str = etree.tostring(root, pretty_print=True)

或转换为元素树

et = etree.ElementTree(root)
et.write(sys.stdout, pretty_print=True)

答案 1 :(得分:5)

这是一个简洁的答案

from lxml import etree

root = etree.Element("root")
root.set("interesting", "somewhat")
child1 = etree.SubElement(root, "test")

my_tree = etree.ElementTree(root)
with open('./filename', 'wb') as f:
    f.write(etree.tostring(my_tree))

您只需将节点放在新树中并将其写入磁盘即可。也适用于xpath搜索生成的HtmlElements

答案 2 :(得分:1)

您可以尝试以下代码。

from lxml import etree as ET

root = ET.Element('Doc')
level1 = ET.SubElement(root, 'S')
main = ET.SubElement(level1, 'Text')
main.text = 'Thanks for contributing an answer to Stack Overflow!'
second = ET.SubElement(level1, 'Tokens')
level2 = ET.SubElement(second, 'Token', word=u"low")


level3 = ET.SubElement(level2, 'Morph')
second1 = ET.SubElement(level3, 'Lemma')
second1.text = 'sdfs'
second1 = ET.SubElement(level3, 'info')
second1.text = 'qw'

level4 = ET.SubElement(level3, 'Aff')
second1 = ET.SubElement(level4, 'Type')
second1.text = 'sdfs'
second1 = ET.SubElement(level4, 'Suf')
second1.text = 'qw'

tree = ET.ElementTree(root)
tree.write('output.xml', pretty_print=True, xml_declaration=True,   encoding="utf-8")

答案 3 :(得分:1)

这对我有用:

et = etree.ElementTree(document)
with open('sample.xml', 'wb') as f:
    et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)

答案 4 :(得分:1)

您可以将文件名提供给ElementTree的write()

etree.ElementTree(root).write('output.xml')