Python: Creating XML documents

It was incredibly simple to create XML structure in Python.

from xml.etree.ElementTree import Element
from xml.etree import ElementTree

# Build the XML
root = Element("products")
root.set('matches', "15")
root.set('search_query', "whatever I searched for")

for p in products:
element = Element('product')
element.set('name', p.name)
element.set('brand', p.brand)
element.set('price', "%s" % p.price) # Convert numbers to strings
root.append(element)

similar = Element('similar')
for sp in p.similar:
similar_element = Element('similar_product')
similar_element.set('id', "%s" % sp.id)
similar_element.set('name', sp.name)
similar_element.set('brand', sp.brand)
similar.append(similar_element)

element.append(similar)

return HttpResponse(ElementTree.tostring(root), content_type = "text/xml")

Source

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog