For serious work with XML in Python use lxml
Python comes with ElementTree built-in library, but lxml extends it in terms of speed and functionality (schema validation, sax parsing, XPath, various sorts of iterators and many other features).
You have to install it, but in many places, it is already assumed to be part of standard equipment (e.g. Google AppEngine does not allow C-based Python packages, but makes an exception for lxml, pyyaml, and few others).
Building XML documents with E-factory (from lxml)
Your question is about building XML document.
With lxml there are many methods and it took me a while to find the one, which seems to be easy to use and also easy to read.
Sample code from lxml doc on using E-factory (slightly simplified):
The E-factory provides a simple and compact syntax for generating XML and HTML:
>>> from lxml.builder import E >>> html = page = ( ... E.html( # create an Element called "html" ... E.head( ... E.title("This is a sample document") ... ), ... E.body( ... E.h1("Hello!"), ... E.p("This is a paragraph with ", E.b("bold"), " text in it!"), ... E.p("This is another paragraph, with a", " ", ... E.a("link", href="http://www.python.org"), "."), ... E.p("Here are some reserved characters: <spam&egg>."), ... ) ... ) ... ) >>> print(etree.tostring(page, pretty_print=True)) <html> <head> <title>This is a sample document</title> </head> <body> <h1>Hello!</h1> <p>This is a paragraph with <b>bold</b> text in it!</p> <p>This is another paragraph, with a <a href="http://www.python.org">link</a>.</p> <p>Here are some reserved characters: <spam&egg>.</p> </body> </html>
I appreciate on E-factory it following things
Code reads almost as the resulting XML document
Allows creation of any XML content
Supports stuff like:
- use of namespaces
- starting and ending text nodes within one element
- functions formatting attribute content (see func CLASS in full lxml sample)
Allows very readable constructs with lists
from lxml import etree from lxml.builder import E lst = ["alfa", "beta", "gama"] xml = E.root(*[E.record(itm) for itm in lst]) etree.tostring(xml, pretty_print=True)
<root> <record>alfa</record> <record>beta</record> <record>gama</record> </root>
I highly recommend reading lxml tutorial - it is very well written and will give you many more reasons to use this powerful library.
The only disadvantage of lxml is, that it must be compiled. See SO answer for more tips how to install lxml from wheel format package within a fraction of a second.