Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write xml file using lxml library in Python

Tags:

python

xml

lxml

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?

like image 480
systempuntoout Avatar asked May 14 '10 09:05

systempuntoout


People also ask

What is lxml library in Python?

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers. This is when the lxml library comes to play.

Is lxml in Python standard library?

There is a lot of documentation on the web and also in the Python standard library documentation, as lxml implements the well-known ElementTree API and tries to follow its documentation as closely as possible. The recipes in Fredrik Lundh's element library are generally worth taking a look at.

What is lxml Etree in Python?

lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.


1 Answers

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) 
like image 150
mmmmmm Avatar answered Sep 17 '22 19:09

mmmmmm