Ionrock Dot Org

by Eric Larson

My Weblog

Writing XML in Code

I have been working with Sylvain recently on Amplee and it has been interesting to see how each of us use Amara. I have always tried to use it like an object as much as possible. What you end up seeing is things like this:

if hasattr(doc.entry, 'title'):
    title = str(doc.entry.title)

Amplee takes a slightly different approach that doesn’t feel as obvious, but is a little safer. I actually like this approach because it feels closer to using a Python dictionary rather than an object.

title = doc.entry.xml_child_elements.get('title')


This is one line, safer for when you don’t actually have the element and doesn’t use the ugly hasattr function. Chalk one up for Sylvain!

Another difference I have noticed is when we write a XML document with Amara. These differences have no actual impact on the code, but I think it is interesting nonetheless.

col.xml_append(doc.xml_create_element(qname(u"title", ATOM10_PREFIX),
                                                       ns=ATOM10_NS, attributes={u'type': u'text'},
                                                       content=collection.title))


The qname function is different to me and the lines are a bit long for my test.

I would do something like this:

col.xml_append(
    doc.xml_create_element(
        u'title', ATOM10_PREFIX,
        attributes={ u'type': u'text'},
        content=collection.title
    )
)


I am not sure this is clearer, but it does present a recognizable pattern over code. In the places I add elements you can see the pattern, which is somewhat helpful. The downside is I think it kind of looks like a C based language, which isn’t as cool ;)

There are other differences as well. I think some of it stems from our backgrounds with different XML technologies. I never really wrapped my head around DOM in a way that I was effective with it. My path would usually lead to a object wrapper. Sylvain though has spent a good deal of time working with the DOM and understands how to use it more fluently. I also have been making a huge effort to keep lines under 80 columns, which is probably why some of my code tends to be longer vertically. It is always interesting to contrast your ideas and code with someone elses so this has been a fun exercise and good learning experience.

Posted Thu Aug 23 15:38:49 2007 by Eric Larson
Created using Python, jQuery and Emacs