Write xml file using lxml library in Python

systempuntoout picture systempuntoout · May 14, 2010 · Viewed 63.7k times · Source

I'm using lxml to create an XML file from scratch; having a code like this:

from lxml import etree

root = etree.Element("root")
root.set("interesting", "somewhat")
child1 = etree.SubElement(root, "test")

How do I write root Element object to an xml file using write() method of ElementTree class?

Answer

mmmmmm picture mmmmmm · May 14, 2010

You can get a string from the element and then write that from lxml tutorial

str = etree.tostring(root, pretty_print=True)

Look at the tostring documentation to set the encoding - this was written in Python 2, Python 3 gives a binary string back which can be written directly to file but is probably not what you want in code.

or convert to an element tree (originally write to a file handle but either missed when I wrote this or it is new it can be a file name as per this answer )

et = etree.ElementTree(root)
et.write('output.xml', pretty_print=True)