jbatista
jbatista

Reputation: 2855

Python framework for object-XML mapping through decorators?

After coming up impressed with the ease of use of the XML serialization framework Simple XML in Java, I've tried looking for a Python counterpart that would facilitate implementing classes and their XML serialization in a similar fashion. So far, I've come up more or less empty-handed, although there are interesting candidates (but none conveniently using decorators, as far as I could tell); for example, I started looking at dexml, but I got stumped with an example as simple as implementing a class that would allow deserialization of

<Error Code="0">OK</Error>

With Simple in Java, I could write a class such as

@Root(name="Error")
public class Error {

    @Attribute(name = "Code")
    private int code;  // public getter and setter

    @Text(required = false) 
    private String description; // public getter and setter
}

Is there already a similar flavored framework in Python as Simple for Java? I have preference for Python 2.6 support, although that's not mandatory; if it's supported only for Python 3 I'll also look into it.

Upvotes: 2

Views: 945

Answers (2)

amy hh.
amy hh.

Reputation: 36

Actually this syntax is supported in dexml. It took me awhile to figure it out (reading the source code helped).

class Error(dexml.Model):
    code = dexml.fields.String()
    value = dexml.fields.String(tagname=".")

And the following will return the xml rendering of desire:

e = Error(code="0",value="OK")
print e.render(fragment=True)

Upvotes: 2

cromulent
cromulent

Reputation: 13

Don't have an answer but will confirm the difficulty of using dexml to parse your example. It doesn't look like there is a way to parse an element with attributes and a text node. Defining the Code attribute is simple:

class Error(dexml.Model):
    code = dexml.fields.String(attrname="Code")

But there is no way to reference a child text node. One would like to do something like:

class Error(dexml.Model):
    code = dexml.fields.String(attrname="Code")
    text = dexml.fields.String(textnode=True)

One not very satisfactory way to capture the text would be to wrap it in extra tags:

<Error Code="0"><text>OK</text></Error>

Then you could define the class as:

class Error(dexml.Model):
    code = dexml.fields.String(attrname="Code")
    text = dexml.fields.String(tagname="text")

Upvotes: 0

Related Questions