写入文件时添加XML声明

时间:2014-03-07 17:22:04

标签: python xml lxml

请帮助了解如何添加xml文档录制类型

例如,

具有以下编写xml-tree文件的代码

def record_xml(xml, fileName='xml.xml'):
    try:
        with open(fileName, "w") as file:
            file.write(xml)
    except Exception:
        print('Error record', Exception)
    else:
        print('record ok')
        return True

record_xml(xmlPretty)

生成的文件只写入xml-tags:

<data>
  <item>
    <message>что с браузером</message>
    <section>Взаимопомощь</section>
    <date>05.07.2013</date>
  </item>
...............
.....

我需要在所有标签之前是一行:

<?xml version="1.0" encoding="utf-8"?>

1 个答案:

答案 0 :(得分:1)

使用xml_declarationencoding参数:

from lxml import etree
xmlPretty = etree.tostring(tree, pretty_print=True, xml_declaration=True, 
                           encoding='utf-8')