我正在使用lxml从头开始创建 XML 文件;有这样的代码:
from lxml import etree
root = etree.Element("root")
root.set("interesting", "somewhat")
child1 = etree.SubElement(root, "test")
如何使用类的方法将根Element
对象写入 xml 文件?write()
ElementTree
您可以从元素中获取一个字符串,然后从lxml 教程中编写它
str = etree.tostring(root, pretty_print=True)
查看 tostring 文档以设置编码 - 这是用 Python 2 编写的,Python 3 提供了一个二进制字符串,可以直接写入文件,但可能不是您想要的代码。
或转换为元素树(最初写入文件句柄,但在我写这个时错过了或者它是新的它可以是根据这个答案的文件名)
et = etree.ElementTree(root)
et.write('output.xml', pretty_print=True)
你可以试试下面的代码。
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")
这是一个简洁的答案
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))
您只需将节点放在新树中并将其写入磁盘。也适用于HtmlElements
由 xpath 搜索产生的。
这对我有用:
et = etree.ElementTree(document)
with open('sample.xml', 'wb') as f:
et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)
您可以将文件名赋予write()
ElementTree
etree.ElementTree(root).write('output.xml')