Creating a simple XML file using python


What are my options if I want to create a simple XML file in python? (library wise)

The xml I want looks like:

     <field1 name="blah">some value1</field1>
     <field2 name="asdfasd">some vlaue2</field2>

8/31/2010 2:38:23 AM

Accepted Answer

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.
10/18/2017 3:29:43 AM

The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:

import lxml.etree
import lxml.builder    

E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2

the_doc = ROOT(
            FIELD1('some value1', name='blah'),
            FIELD2('some value2', name='asdfasd'),

print lxml.etree.tostring(the_doc, pretty_print=True)


    <field1 name="blah">some value1</field1>
    <field2 name="asdfasd">some value2</field2>

It also supports adding to an already-made node, e.g. after the above you could say

the_doc.append(FIELD2('another value again', name='hithere'))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow