用双引号写 lxml.etree header 属性

Writing lxml.etree with double quotes header attributes

我使用 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>

我的问题是,如何使用双引号文件 header 生成 xml 文件,即

<?xml version="1.0" encoding="UTF-8"?>
....

我现在唯一的解决方案是这个功能:

def wrTmp(treeObject, filepath):
    xml_str = ('<?xml version="1.0" encoding="UTF-8"?>' + '\n' +
               etree.tostring(treeObject, pretty_print=True, encoding="UTF-8",
                              xml_declaration=False))
    with open(filepath, 'wb') as xml_file:
        xml_file.write(xml_str)

该函数连接两个字符串。一个带有文件头和换行符,第二个带有 xml 树的其余部分。

有谁知道更"Pythonic"的方法吗?

要在不手动连接的情况下添加 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"?>'
            ))