Monday 23 November 2009

XML Namespaces

Recently I have been lucky enough to be working on a project that uses LCDS so I don’t have to write XML translators – all the objects arrive from server ready typed – it is soooo much easier and saves an awful lot of time.

At home though I have started working with the Picasa data API which means I am back to writing translators.
This is a job I really don’t like – it never works the first time and takes a lot of trial and error to get it write. I am actually going to write a base translator class to make it a bit easier the next time I have to do it.

Getting to grips with xml can be tricky but when namespaces are involved it gets exponentially more difficult and annoying!

I’ll make a note of the syntax of how to deal with namespaces here so that next time I’ve forgotten how to do it I can look it up.

I am trying to retrieve the href of the link node below with the relevance of self:

<feed
    xmlns='http://www.w3.org/2005/Atom'
    xmlns:gphoto='http://schemas.google.com/photos/2007'
    >
    <link
        rel='alternate'
        type='text/html'
        href='http://picasaweb.google.com/Giles.Roadnight'
        />
    <link
        rel='self'
        type='application/atom+xml'
       href='http://picasaweb.google.com/data/feed/api/user/Giles.Roadnight'
        />
</feed>

My first attempt was as follows:

var href : String = xml.link(@rel=’self’)[ 0 ]@href;

but that didn’t work. The give away is this line:

xmlns='http://www.w3.org/2005/Atom'

declaring the default namespace for the xml. What worked in the end was this:

var atom : Namespace = new Namespace( "http://www.w3.org/2005/Atom" );
var href : String = xml.atom::link.( @rel == 'self' )[ 0 ]@href;

Hopefully that’ll save me (and maybe you) a few hours in the future.

4 comments:

  1. Have you looked at using xml to object mapping from the Spicelib library?

    ReplyDelete
  2. I was going to say the same thing. Also, on the roadmap for Spicelib are some improvements so you can configure the mapping through metadata.

    ReplyDelete
  3. Thanks for the heads up. I've had a quick look at the docs and it seems like a really easy way to do the deserialisation. I'll give it ago and report back.

    ReplyDelete
  4. I had problems with parsing flickr feed because i didn't use XML namespaces in my code. I found your post and my problem went away.


    Thanks!!!

    ReplyDelete