Best way to generate xml?
Question: I'm creating an web api and need a good way to very quickly generate some well
formatted xml. I cannot find any good way of doing this in python.

Note: Some libraries look promising but either lack documentation or only
output to files.


Answer: [ElementTree](http://docs.python.org/library/xml.etree.elementtree.html) is a
good module for reading xml and writing too e.g.

    
    
    from xml.etree.ElementTree import Element, SubElement, tostring
    
    root = Element('root')
    child = SubElement(root, "child")
    child.text = "I am a child"
    
    print tostring(root)
    

Output:

    
    
    <root><child>I am a child</child></root>
    

See this
[tutorial](http://www.doughellmann.com/PyMOTW/xml/etree/ElementTree/create.html)
for more details and how to pretty print.

Alternatively if your XML is simple, do not underestimate the power of string
formatting :)

    
    
    xmlTemplate = """<root>
        <person>
            <name>%(name)s</name>
            <address>%(address)s</address>
         </person>
    </root>"""
    
    data = {'name':'anurag', 'address':'Pune, india'}
    print xmlTemplate%data
    

Output:

    
    
    <root>
        <person>
            <name>anurag</name>
            <address>Pune, india</address>
         </person>
    </root>
    

You can use string.Template or some template engine too, for complex
formatting.

