Chris Umbel

NSXML-like XPath Support in Cocoa Touch with TouchXML

I haven't done any real, serious iPhone development until recently. Sure, I tooled around a bit and even had a few false starts on projects, but not much came out. What killed me was that I had no real *idea*. Without a concrete goal in mind it was especially hard to wade through a platform so different from those which I'm used to.

Well, that changed recently. I got an idea. Not a great one, but a good enough idea to keep me at my mac hacking something out. What's the idea? Well, I'm certainly not going to tell you yet! Besides, the actual app I'm writing isn't the focus of this post.

What is, however, is TouchXML which is, according to their website, "a lightweight replacement for Cocoa's NSXML cluster of classes". Why is that important? Because the iPhone SDK does not include NSXML which means no XPath.

Now, I don't know about you, but no XPath cramps my style! My style being cramped was another thing that caused me to have trouble focusing on the platform in the past.

Luckily, thanks to TouchXML it's about as easy as in standard Cocoa. I'll show you my typical example which gets a twitter user's status. Normally I reserve that for out-of-the-box libraries but I'm willing to make an exception here.

Assuming you've downloaded TouchXML, included it in your project like this tutorial describes and

#import "TouchXML.h"

then you can

/* create a url pointing to my status */
NSURL *url = [NSURL URLWithString: @""];
/* have TouchXML parse it into a CXMLDocument */
CXMLDocument *doc = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
/* execute some XPath which will return all status texts (will only be one) */
NSArray *resultNodes = [doc nodesForXPath:@"/user/status/text" error:nil];
NSString *status = @"";
/* pull the text element out, there should only be one so we'll just grab the first */
CXMLElement *resultElement = [resultNodes objectAtIndex:0];
/* pull the status string out  */
status = [resultElement stringValue];

and my twitter status is slapped into the status variable thusly.

So now that my style's not cramped and I have an idea I'm ready to code!

Sun Jan 03 2010 21:44:00 GMT+0000 (UTC)

Follow Chris
RSS Feed