转自:http://liucheng.easymorse.com/?p=112
准备工作:
- 去http://code.google.com/p/touchcode/downloads/list下载最新的TouchXML代码包
- 将TouchXML加入到工程中
- 因为TouchXML使用了libxml2,所以需要添加libxml2 library,在工程编译选项中按下图操作
- 在您的文件中加上
#import "TouchXML.h"
使用TouchXML:
TouchXML使用Xpath方式进行XML Parser
如下xml文件:
<pigletlist> <piglet id="1"> <name>Nifnif</name> </piglet> <piglet id="2"> <name>Nufnuf</name> </piglet> <piglet id="3"> <name>Nafnaf</name> </piglet> </pigletlist>
parser代码如下:
// we will put parsed data in an a array
NSMutableArray *res = [[NSMutableArray alloc] init];// using local resource file
NSString *XMLPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@”piglets.xml”];
NSData *XMLData = [NSData dataWithContentsOfFile:XMLPath];
CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:XMLData options:0 error:nil] autorelease];NSArray *nodes = NULL;
// searching for piglet nodes
nodes = [doc nodesForXPath:@"//piglet" error:nil];for (CXMLElement *node in nodes) {
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [node childCount]; counter++) {
// common procedure: dictionary with keys/values from XML node
[item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
}// and here it is – attributeForName! Simple as that.
[item setObject:[[node attributeForName:@"id"] stringValue] forKey:@”id”];// <—— this magical arrow is pointing to the area of interest
[res addObject:item];
[item release];
}// and we print our results
NSLog(@”%@”, res);
[res release];
parser结果如下:
2010-02-05 09:54:01.078 demo[1901:207] (
{
id = 1;
name = Nifnif;
},
{
id = 2;
name = Nufnuf;
},
{
id = 3;
name = Nafnaf;
}
)