python - 用双引号 header 属性编写 lxml.etree

标签 python lxml

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

相关文章:

python - 通过 Cygwin 运行 Python 脚本的问题

python - 如何过滤 Pandas 系列索引中的字符串

python - lxml:当html标签文本内容为None时附加 'None'或Null值

python - 在解析之前使用 lxml 注册命名空间

python - 网络抓取电话号码

python , Pandas : how to remove greater than sign

python - 连接两列后的 Django 查询集过滤器

python - 在另一个子进程仍在运行时调用子进程,可以吗?

Python 无法将变量添加到 XML

python xpath 返回空列表