这篇文章旨在给自己以后需要时能及时的查到,省得每次都去baidu.
1. xml解析库-GDataXML
参考文章:http://blog.csdn.net/tangren03/article/details/7868246
GDataXML下载地址:
(1)GDataXML.h/m文件
http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/
(2)DGataDefines.h GDataTargetNamespace.h 文件
http://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/
配置过程:
(1).引入GDataXML(4个文件)
<arc模式下>.对GDataXML.m增加非arc注释 -fno-objc-arc
(2).添加系统库 libxml2.dylib
(3).Head Search Path中添加 /usr/include/libxml2
(4).Other linker flags中添加 -lxml2
(5).xml格式
==================================
<?xml version="1.0" encoding="utf-8"?>
<Users>
<User id="001">
<name>Ryan</name>
<age>24</age>
</User>
<User id="002">
<name>Tang</name>
<age>23</age>
</User>
</Users>
==================================
(6).应用
==================================
//获取工程目录的xml文件
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"users" ofType:@"xml"];
NSData *xmlData = [[NSData alloc] initWithContentsOfFile:filePath];
//使用NSData对象初始化
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil];
//获取根节点(Users)
GDataXMLElement *rootElement = [doc rootElement];
//获取根节点下的节点(User)
NSArray *users = [rootElement elementsForName:@"User"];
for (GDataXMLElement *user in users) {
//User节点的id属性
NSString *userId = [[user attributeForName:@"id"] stringValue];
NSLog(@"User id is:%@",userId);
//获取name节点的值
GDataXMLElement *nameElement = [[user elementsForName:@"name"] objectAtIndex:0];
NSString *name = [nameElement stringValue];
NSLog(@"User name is:%@",name);
//获取age节点的值
GDataXMLElement *ageElement = [[user elementsForName:@"age"] objectAtIndex:0];
NSString *age = [ageElement stringValue];
NSLog(@"User age is:%@",age);
NSLog(@"-------------------");
}