Skip to content

Instantly share code, notes, and snippets.

@FelixSchwarz
Created December 31, 2013 14:03
Show Gist options
  • Save FelixSchwarz/8197203 to your computer and use it in GitHub Desktop.
Save FelixSchwarz/8197203 to your computer and use it in GitHub Desktop.
example implementation to serialize a given model to xml: https://mail.python.org/pipermail/python-de/2013q4/003488.html
from lxml import etree
from soapbox import xsd
class Actor(xsd.ComplexType):
name = xsd.Element(xsd.String)
role = xsd.Element(xsd.String)
class Actors(xsd.ComplexType):
actor = xsd.Element(Actor)
class Movie(xsd.ComplexType):
title = xsd.Element(xsd.String)
original = xsd.Element(xsd.String, nillable=True)
url = xsd.Element(xsd.String, nillable=True)
actors = xsd.Element(Actors)
runtime = xsd.Element(xsd.Integer)
aspect_ratio = xsd.Element(xsd.String)
expected_xml = "<movie><title>Ein Hauch von Nerz</title>" \
+ "<original>That Touch of Mink</original>" \
+ "<url>http://de.wikipedia.org/wiki/Ein_Hauch_von_Nerz</url>" \
+ "<actors><actor><name>Sean Connery</name><role>James Bond</role></actor></actors>" \
+ "<runtime>94</runtime>" \
+ "<aspect_ratio>16:9 - 1.77:1</aspect_ratio>" \
+ "</movie>"
actor = Actor()
actor.name = 'Sean Connery'
actor.role = 'James Bond'
actors = Actors()
actors.actor = actor
movie = Movie()
movie.title = "Ein Hauch von Nerz"
movie.original = "That Touch of Mink"
movie.url = "http://de.wikipedia.org/wiki/Ein_Hauch_von_Nerz"
movie.actors = actors
movie.aspect_ratio = "16:9 - 1.77:1"
movie.runtime = 94
document = etree.Element('movie')
movie.render(document, movie)
serialized_xml = etree.tostring(document, pretty_print=True)
assert etree.tostring(etree.fromstring(expected_xml), pretty_print=True) == serialized_xml
print 'generated xml is valid'
parsed = Movie.parsexml(expected_xml)
assert 'Sean Connery' == parsed.actors.actor.name
print 'was able to parse actor name'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment