如何将XML声明写入XML文件?

时间:2016-09-01 03:54:06

标签: python xml

我目前正在使用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电子邮件模板PUBLIC“ - // yourcompany,Inc.//DTD email-template // EN”“email-template.dtd”&gt;

如何将此信息写入XML文件?

1 个答案:

答案 0 :(得分: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')  
相关问题