开发者

How to read and parse an .xml file

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

<exchanges>
    <exchange&g开发者_如何转开发t;
        <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


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"];

}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜