Document-based vs. event-driven XML parsing

When I wrote my FriendFeed Cocoa classes, I used the document-based NSXMLDocument class, which I later found out isn’t available on the iPhone. However, there’s an alternative that’s available both in Mac OS X and the iPhone: NSXMLParser, which uses an event-driven approach.

While the two approaches are very different, I found that it isn’t too difficult to rewrite my code to use XMLParser. I’ve been working on a fun iPhone app using the Flickr API and I found that the event driven approach is very easy to use.

With NSXMLDocument, I called the parser and then iterated through the resulting collection of elements, creating my own objects from each element. With NSXMLParser, on the other hand, my callback methods get called for each element, which I can then use to create my own object in a very similar way. A single element with several attributes, such as Flickr’s response format, is very easy to deal with since it can be handled in its entirety with a single method. An element with child elements, such as FriendFeed uses, is only slightly more difficult. I need to use both the start element & end element methods for the parent element.

After I finish the Flickr app, I plan to rewrite my FriendFeed class to work on the iPhone.

Leave a Comment