【问题标题】:how to write XML declaration into XML file? [duplicate]如何将 XML 声明写入 XML 文件? [复制]
【发布时间】:2017-01-08 19:15:28
【问题描述】:

我目前正在使用 ElementTree 编写一个 XML 文件

for i in range(len(lang_list)):
    body = ET.SubElement(root, "body")
    body.set("lang", lang_list[i])
    # body.text = text_list[i] + " " + common_text
    body.text =unescape(escape('<![CDATA[')) + text_list[i] + " " +     common_text + unescape(escape(']]>'))
    body.tail = "\n\t"

outpath = os.getcwd()
file = outpath + "\\test.xml"
tree.write(file, xml_declaration=True)

但是有一个XML声明,比如

DOCTYPE email-template PUBLIC "-//yourcompany, Inc.//DTD email-template//EN" "email-template.dtd">

如何将这些信息写入 XML 文件?

【问题讨论】:

  • 我在这里写了一个答案,但问题在我提交之前就关闭了。你可以看到我的回答here

标签: python xml


【解决方案1】:

一个可能的(务实的)解决方案是替换你的最后一行

tree.write(file, xml_declaration=True)

with open(file, 'wb') as f:
    f.write(b'<?xml version="1.0" encoding="UTF-8"?>');
    f.write(b'<!DOCTYPE email-template PUBLIC "-//yourcompany, Inc.//DTD email-template//EN" "email-template.dtd">')
    tree.write(f, xml_declaration=False, encoding='utf-8')  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多