`
hunxiejun
  • 浏览: 1144217 次
文章分类
社区版块
存档分类
最新评论

[转] 使用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;
}
)

分享到:
评论

相关推荐

    TouchXML使用教程

    使用TouchXML在iPhone开发、iPad开发中实现XML_Parser

    iOS的XML解析库 TouchXML.zip

    iOS的XML解析库 TouchXML ,TouchXML 是使用 Objective-C 编写的 XML 解析器,适合在 iOS 和 Mac...

    iphone,xml多种解析方法

    GDataXML,TinyXML,KissXML,TouchXML,TBXML多种xml解析例子,不多说需要的自己下来看看吧!

    iOS开发中常见的解析XML的类库以及简要安装方法

    在iPhone开发中,XML的解析有很多选择,iOS SDK提供了NSXMLParser和libxml2两个类库,另外还有很多第三方类库可选,例如TBXML、TouchXML、KissXML、TinyXML和GDataXML。问题是应该选择哪一个呢? 解析 XML 通常有两...

    cocos2d 2.0配置TouchXML

    1、TouchXML资源包 2、在cocos2d 2.0,XCode 4.3.3环境下配置TouchXML,详图亲测。 3、TouchXML实例解析。

    BlogTutorial.zip

    Xml解析源代码,把TouchXML文件夹copy到工程中,具体操作看一下转载的文章

    iOS 4 高级编程

    • Parsing XML documents using SAX, DOM, and TouchXML • Working with the Map Kit API • Remote and local push notification • Multitasking • Working with the address book • Consuming RESTful web ...

    iOS源代码-英汉互译

    用ios5.1做的英汉互译软件,有单词本功能,用storyboard做的,sqlite存储数据,详细见文档

Global site tag (gtag.js) - Google Analytics