views:

100

answers:

3

I need to simply read an .xml file; like this:

<exchanges>
    <exchange>
        <timestamp>2010-08-19 17:15:56</timestamp>
        <userid>Elijah-Woods-MacBook-Pro.local</userid>
        <clientname>elijah</clientname>
        <botid>Jarvis</botid>
        <input>firsthello</input>
        <response>Hello, sir. How may I help you?</response>
    </exchange>
</exchanges>

Then, parse whatever's in between the 'response' tag.

Elijah

A: 

You have two choices for parsing XML in Cocoa:

  1. Event-Driven, in which the parser emits events to which your delegate class responds.
  2. Tree-Based, in which the parser builds an XML tree that you can query or modify.

Event-driven parsing is less memory-intensive, but since you don't build a whole XML tree, you can't use XPath or XQuery to get information about the document. Tree-based generally uses more memory (since the entire XML document is converted into a object form and stored in memory), but it offers more powerful mechanisms for getting data out of the tree.

mipadi
Can you show a quick example to parse this and just get what's in-between the response tag? This is all I need.
Elijah W.
This .XML file is located on my desktop.
Elijah W.
A: 

TouchXML is also a very good library for XML on iPhone. It is been proved to be one of the fastest for parsing too.

Here is an examples project: http://dblog.com.au/general/iphone-sdk-tutorial-building-an-advanced-rss-reader-using-touchxml-part-1/

There are many more online if you good "touchxml iphone tutorial" though

jodm
I'm mainly using this for Mac. Any similar thing for Mac?
Elijah W.
TouchXML is just a replacement for Cocoa's NSXML* classes (NSXML* doesn't exist on the iPhone).
mipadi
+1  A: 

Basic idea, the code is not complete.. based on GDataXML

http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/

also see this analysis of multiple parsers

http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project

NSArray *entries = [doc nodesForXPath:@"//exchanges/exchange" error:nil];
for (GDataXMLElement *entry in entries) {
    NSMutableDictionary * dict = [[[NSMutableDictionary alloc]initWithCapacity:7 ] autorelease];
    [dict setValue:[[[entry elementsForName:@"timestamp"] objectAtIndex:0] stringValue] forKey:@"timestamp"];
    [dict setValue:[[[entry elementsForName:@"userid"] objectAtIndex:0] stringValue] forKey:@"userid"];
    [dict setValue:[[[entry elementsForName:@"clientname"] objectAtIndex:0] stringValue] forKey:@"clientname"];
    [dict setValue:[[[entry elementsForName:@"botid"] objectAtIndex:0] stringValue] forKey:@"botid"];
    [dict setValue:[[[entry elementsForName:@"input"] objectAtIndex:0] stringValue] forKey:@"input"];
    [dict setValue:[[[entry elementsForName:@"response"] objectAtIndex:0] stringValue] forKey:@"response"];

}
Aaron Saunders