Python software that maps objects to XML is incredibly easy to use.
Inspired by Django’s ORM, with dexml, you write straightforward class definitions that define the expected structure of your XML document. This software takes the obvious mapping between XML tags and Python objects and captures it in an easy-to-understand manner.
With Dexml, you can parse an XML document into an object easily. For instance, if you have a Person class, you could easily parse an XML document into this object as shown below:
>>> import dexml
>>> from dexml import fields
>>> class Person(dexml.Model):
... name = fields.String()
... age = fields.Integer(tagname='age')
>>> p = Person.parse("< Person name='Foo McBar' >< age >42< /age >< /Person >")
>>> p.name
u'Foo McBar'
>>> p.age
42
You can also convert an object into an XML document. Here's an example:
>>> p = Person(name="Handsome B. Wonderful",age=36)
>>> p.render()
'< ?xml version="1.0" ? >< Person name="Handsome B. Wonderful" >< age >36< /age >< /Person >'
Dexml comes with error handling abilities. For example, if you try to parse a malformed document, it will raise a ParseError. Here's an example:
>>> p = Person.parse("< Person >< age >92< /age >< /Person >")
>>> Traceback (most recent call last):
... ParseError: required field not found: 'name'
You can also nest Model definitions, making it more interesting. Here's an example of how to define a Group class that nests the Person model:
>>> class Group(dexml.Model):
... name = fields.String(attrname="name")
... members = fields.List(Person)
...
>>> g = Group(name="Monty Python")
>>> g.members.append(Person(name="John Cleese",age=69))
>>> g.members.append(Person(name="Terry Jones",age=67))
>>> g.render(fragment=True)
'< Group name="Monty Python" >< Person name="John Cleese" >< age >69< /Person >< Person name="Terry Jones" >< age >67< /age >< /Person>< /Group >'
Lastly, Dexml also has support for XML namespaces, default field values, case-insensitive parsing as well as many other fantastic features. For more details on the classes, check out the documentation on the following classes:
- Model – the base class for objects that map into XML
- Field – the base class for individual model fields
- Meta – meta-information about how to parse/render a model.
Version 0.2.0: N/A