这里主要介绍一下由Google提供的一种在IOS平台上进行XML解析的开源库GdataxML,可以到http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/下载源码,下载下来后进入文件夹找到XMLSupport文件夹,将里面的GdataxMLNode.h和GdataxMLNode.m文件拖拽到项目
注:
1.targets ->build settings 的other linker flags 添加字段 -lxml2
2.targets ->build settings 的headersearch Paths 添加字段/usr/include/libxml2
3.导入 libxml2.dylib 系统库
例如解析:
<?xml version="1.0" encoding="utf-8"?>
<Users>
<User id="001">
<name>Ryan</name>
<name>hjhj</name>
<age>24</age>
</User>
<User id="002">
<name>Tang</name>
<name>Tangss</name>
<age>23</age>
</User>
<User id="003">
<name>Tanssg</name>
<name>Tansdsg</name>
<age>2ssss3</age>
</User>
</Users>
使用GdataxMLNode 解析
//获取工程目录xml文件 NSString *filePach = [[NSBundle mainBundle]pathForResource:@"Users" ofType:@"xml"]; NSData *xmlData = [[NSData alloc]initWithContentsOfFile:filePach]; //使用nsdata对象初始化 GdataxMLDocument *doc = [[GdataxMLDocument alloc]initWithData:xmlData options:0 error:nil]; //获得跟节点(Users) GdataxMLElement *rootElement = [doc rootElement]; //获取跟节点下的节点 NSArray *users = [rootElement elementsForName:@"User"]; for (GdataxMLElement *user in users) { //user节点属性 NSString *userId =[[user attributeForName:@"id"]stringValue]; NSLog(@"userId = %@",userId); //获取name节点的值 GdataxMLElement *nameElement = [[user elementsForName:@"name"]objectAtIndex:1]; NSString *name = [nameElement stringValue]; NSLog(@"name = %@",name); //获取age节点的值 GdataxMLElement *ageElement = [[user elementsForName:@"age"]objectAtIndex:0]; NSString *age = [ageElement stringValue]; NSLog(@"age = %@",age); NSLog(@"==================="); }