我使用lxml 教程创建了一个基本的 xml 树:
from lxml import etree
root = etree.Element("root")
root.append( etree.Element("child1") )
child2 = etree.SubElement(root, "child2")
child3 = etree.SubElement(root, "child3")
print(etree.tostring(root, pretty_print=True, encoding="UTF-8", xml_declaration=True))
Run Code Online (Sandbox Code Playgroud)
这会产生以下结果:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<child1/>
<child2/>
<child3/>
</root>
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何生成带有双引号文件头的xml文件,即
<?xml version="1.0" encoding="UTF-8"?>
....
Run Code Online (Sandbox Code Playgroud)
小智 6
要在不手动连接的情况下添加标头,您需要在 tostring 方法中使用“doctype”参数,如下所示:
with open(output_file, 'wb') as o:
o.write(etree.tostring(
document_root, pretty_print=True,
doctype='<?xml version="1.0" encoding="ISO-8859-1"?>'
))
Run Code Online (Sandbox Code Playgroud)