APXML: NSXMLDocument ‘substitute’ for iPhone/iPod Touch
After spending some time working on Jabeh, my latest creation for iPhone/iPod Touch, I’m taking some time to dump a little learned knowledge into my blog.
In my first app, my XML needs weren’t that great, so putting up with the lack of
NSXMLDocument in the iPhone SDK was not a big deal. However, in Jabeh I was changing the XML format so often and using so much of it for my network communication creating delegates for
NSXMLParser quickly became a huge time sink. After a little hacking, I came up with APXML to solve my DOM problem. It’s not a perfect implementation of the W3C XML 1.0 standard, but it’s close enough for a lot of usage. One particular shortcoming is its lack of support for namespaces but maybe somebody else can add that support. If you just want to jump in and start using it (LGPL license), you can get the code from github:
Most of my XML manipulation experience has been with various Java libraries (org.w3c.dom interface, JDOM and XOM), and the only one that I enjoyed using was XOM, because of its simplicity and licensing. Almost all of my design decisions were based on how XOM does things.
Let’s say we want to represent the following XML document in memory using APXML:
In code, we do the following:
And if we want to convert the document to an
NSString*, we use one of the two methods in
Often times when I’m working with XML, I like to see what the current element contains, so for added convenience, you can obtain an XML string containing the element you’re working with, its attributes and all its children directly from the
APElement by calling one of two methods:
Now for the best part of the library, which is the ability to read in XML and represent it in APXML. All you have to execute is one simple line:
Hopefully this will be helpful to other developers out there. I may post another article soon if anybody has some questions.
UPDATE Sep 5, 2009: Here’s an example that demonstrates traversing the XML document.
In the console you’ll see (I’ve removed the
Root Element Name: books Child Name: book Author: Michael Pollan Title: The Omnivore’s Dilemma Child Name: book Author: Foley, van Dam, Feiner, Hughes Title: Computer Graphics: Principles and Practices