systempuntoout
systempuntoout

Reputation: 74094

Write xml file using lxml library in Python

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?

Upvotes: 70

Views: 97435

Answers (5)

mmmmmm
mmmmmm

Reputation: 32661

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)

Upvotes: 92

korakot
korakot

Reputation: 40818

You can give the filename to the write() of ElementTree

etree.ElementTree(root).write('output.xml')

Upvotes: 3

Soraya Anvari
Soraya Anvari

Reputation: 189

This works for me:

et = etree.ElementTree(document)
with open('sample.xml', 'wb') as f:
    et.write(f, encoding="utf-8", xml_declaration=True, pretty_print=True)

Upvotes: 7

Harry Moreno
Harry Moreno

Reputation: 11603

Here's a succinct answer

from lxml import etree

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

my_tree = etree.ElementTree(root)
with open('./filename', 'wb') as f:
    f.write(etree.tostring(my_tree))

you simply place your node in a new tree and write that out to disk. Also works for HtmlElements produced by xpath searches.

Upvotes: 8

Kairat Koibagarov
Kairat Koibagarov

Reputation: 1475

You can try the below code.

from lxml import etree as ET

root = ET.Element('Doc')
level1 = ET.SubElement(root, 'S')
main = ET.SubElement(level1, 'Text')
main.text = 'Thanks for contributing an answer to Stack Overflow!'
second = ET.SubElement(level1, 'Tokens')
level2 = ET.SubElement(second, 'Token', word=u"low")


level3 = ET.SubElement(level2, 'Morph')
second1 = ET.SubElement(level3, 'Lemma')
second1.text = 'sdfs'
second1 = ET.SubElement(level3, 'info')
second1.text = 'qw'

level4 = ET.SubElement(level3, 'Aff')
second1 = ET.SubElement(level4, 'Type')
second1.text = 'sdfs'
second1 = ET.SubElement(level4, 'Suf')
second1.text = 'qw'

tree = ET.ElementTree(root)
tree.write('output.xml', pretty_print=True, xml_declaration=True,   encoding="utf-8")

Upvotes: 13

Related Questions