Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to generate xml? [duplicate]

Tags:

python

xml

api

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.

like image 613
Joshkunz Avatar asked Oct 02 '10 04:10

Joshkunz


People also ask

Can Python create XML?

Extensible Markup Language(XML), is a markup language that you can use to create your own tags.

What is XML Generator?

The XML Generator is a powerful tool for automatically generating XML instance documents which conform to any XML Schema data model. (illustrated below - click to enlarge). The generation of the sample XML files can be customized according to your preferences, and always results in valid, well-formed XML.


2 Answers

Using lxml:

from lxml import etree  # create XML  root = etree.Element('root') root.append(etree.Element('child')) # another child with text child = etree.Element('child') child.text = 'some text' root.append(child)  # pretty string s = etree.tostring(root, pretty_print=True) print s 

Output:

<root>   <child/>   <child>some text</child> </root> 

See the tutorial for more information.

like image 22
ars Avatar answered Sep 19 '22 18:09

ars


ElementTree 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 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.

like image 94
Anurag Uniyal Avatar answered Sep 18 '22 18:09

Anurag Uniyal