我使用 lxml tutorial 创建了一个基本的 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))
这会产生以下内容:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<child1/>
<child2/>
<child3/>
</root>
我的问题是,如何生成带有双引号文件头的 xml 文件,即
<?xml version="1.0" encoding="UTF-8"?>
....
最佳答案
要在不手动连接的情况下添加 header ,您需要在 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"?>'
))
关于python - 用双引号 header 属性编写 lxml.etree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46566216/