既然要使用touchXml解析xml。那么首先应该下载touchxml类库。猛击我。点击左边的zip下载。
打开下载好的类库。找到里面的Source文件夹。这就是需要用到的类库。
然后在xcode建立一个项目。在项目中新建一个文件夹,名字随便,就叫touchxml吧。然后将Source中的文件
拖入touchxml文件夹中。尽量将Copy itmes into destination group’s folder(if needed)勾选上。
这时候,你编译他是不会通过的。你需要首先添加libxml2 library。右键Frameworks。通过下面的操作
找到libxml2.dylib添加到工程中。这还没有结束,不能使用touchxml。还需要在工程选项中进行配置。
点击project-》Edit Porject Settings。在窗口的搜索栏中输入 header search.然后双击
Header Search Paths 后面空白。点击左下角+,打上对号,然后在Path中输入/usr/include/libxml2
在搜索框中输入other linker flags 。添加上字符-lxml2。然后command +B编译,success。
这个,我们就来个练习用一下这个touchxml。
起手我们用它的时候,先在项目里建立一个xml文件。没有xml解析什么呀。~~~~!
在Resources文件夹下Add-》New File,选择Mac OS x下的 Resource。然后选择stringFile。
文件名随意,就xmlfile.xml吧。内容可以复制下面的内容。
<books> iphonebook> id>01</name>iPhoneDeveloper'spage>123>02>ipadDeveloper's>220wp7book>03>wp7developer>281 >04>windows phone 7>300> >
直接上代码说话吧。。。。记得引用它的头文件。#import "TouchXML.h"
- (void)viewDidLoad { //获得文件路径 NSString *XMLPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"userInfo.xml"]; 取得数据 NSData *XMLData = [NSData dataWithContentsOfFile:XMLPath]; 生成CXMLDocument对象 CXMLDocument *document = [[CXMLDocument alloc] initWithData:XMLData options:0 error:nil ];
[self parseDire:document]; [self parseRoot:document]; [super viewDidLoad]; }
[self parseDire:document];
[self parseRoot:document];这两个是两种解析的方式,可以分别尝试下。
void ) parseDire:(CXMLDocument *) document { NSArray *books = NULL; books = [document nodesForXPath: //iphonebook" error:nil]; for (CXMLElement *element in books) { if ([element isKindOfClass:[CXMLElement class]]) { NSMutableDictionary *item = [[NSMutableDictionary alloc] init]; for ( int i = 0; i < [element childCount]; i++) { if ([[[element children] objectAtIndex:i] isKindOfClass:[CXMLElement class]]) { [item setObject:[[element childAtIndex:i] stringValue] forKey:[[element childAtIndex:i] name] ]; NSLog( %@",[[element childAtIndex:i] stringValue]); } } NSLog(@"%@",item);
} } //
books = [document nodesForXPath: //wp7book
} } }
-------------------------------
void) parseRoot:(CXMLDocument *) document { CXMLElement *root = [document rootElement]; NSArray *books = [root children]; 0; i < [element childCount]; i++) { class]]) { if ([[element name] isEqualToString:iphonebook"]) { [item setObject:[[element childAtIndex:i] stringValue] forKey:[[element childAtIndex:i] name]]; NSLog(1%@ } wp7book2%@ } } }
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|