[转] 使用TouchXML在iPhone中实现XML Parser

转自:http://liucheng.easymorse.com/?p=112

 

准备工作:

  1. http://code.google.com/p/touchcode/downloads/list下载最新的TouchXML代码包
  2. 将TouchXML加入到工程中


  3. 因为TouchXML使用了libxml2,所以需要添加libxml2 library,在工程编译选项中按下图操作

  4. 在您的文件中加上
     #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;
}
)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值