5

iOS开发小记:XML解析(GDataXML)

 1 year ago
source link: https://www.isaced.com/post-199.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

iOS开发小记:XML解析(GDataXML)

xml

貌似很久没有发文了,今天把前两天弄的IOS XML解析记录下来,也供大家参考。

GDataXML是Google开发的一个XML解析库,轻便,特点使用非常简单,支持XPath。

GoogleCode :https://code.google.com/p/gdata-objectivec-client/source/browse/trunk/Source/XMLSupport/

由于使用的SVN,没装只好自己Copy下来了,不过可恶的是版本太老了,看注释是08年写的,到现在都5年了,不支持ARC,还要添加点编译命令,可看:《ARC与非ARC工程互相调用》。

第一步,加入框架:libxml2.dylib

第二步,设置 Search Paths 中 Header Search Paths 为 /usr/include/libxml2

第三步,导入头文件:GDataXMLNode.h

然后帖个例子,也是在别人站上看到的,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>
//获取工程目录的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(@"-------------------");  
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK