Sergey
Sergey

Reputation: 167

Add XML declaration when writing to a file

please help to understand how you can add the type of xml-document recording

for example, have the following code that writes the xml-tree file

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)

resulting file is written only xml-tags:

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

and I need to before all the tags was a line:

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

Upvotes: 1

Views: 131

Answers (1)

zhangxaochen
zhangxaochen

Reputation: 34017

Use xml_declaration and encoding params:

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

Upvotes: 1

Related Questions