github.com/hoffmann Peter Hoffmann on Stackoverflow @peterhoffmann on twitter Peter Hoffmann on Facebook Contact me per email Subscribe to Atom Feed

Peter Hoffmann

Software Engineer
prev page next page

How do I convert XML to nested objects

Posted on January 7, 2009
#stackoverflow #python

This my Answer to the stackoverflow question: How do I convert XML to nested objects:

It's worth to have a look at http://codespeak.net/lxml/objectify.html

>>> xml = """<main>
... <object1 attr="name">content</object1>
... <object1 attr="foo">contenbar</object1>
... <test>me</test>
... </main>"""

>>> from lxml import objectify

>>> main = objectify.fromstring(xml)

>>> main.object1[0]
'content'

>>> main.object1[1]
'contenbar'

>>> main.object1[0].get("attr")
'name'

>>> main.test
'me'

Or the other way around to build xml structures:

>>> item = objectify.Element("item")

>>> item.title = "Best of python"

>>> item.price = 17.98

>>> item.price.set("currency", "EUR")

>>> order = objectify.Element("order")

>>> order.append(item)

>>> order.item.quantity = 3

>>> order.price = sum(item.price * item.quantity
... for item in order.item)

>>> import lxml.etree

>>> print lxml.etree.tostring(order, pretty_print=True)
<order>
  <item>
    <title>Best of python</title>
    <price currency="EUR">17.98</price>
    <quantity>3</quantity>
  </item>
  <price>53.94</price>
</order>