//使用GDdata去做xml解析;
//1.导入第三方库GData;
//Gdata是基于系统的libzml2库去实现xml的解析;libxml2
//默认没有被导入工程中,需要手动导入
//具体步骤参见上一条博客
#import <Foundation/Foundation.h>
#import "GdataxMLNode.h"
#define path @"http://yuting.local/shareX/xml2.xml"
int main(int argc,const char * argv[]) {
//1.拿到需要解析的数据
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
// NSString * str = [[NSString alloc]initWithData:data
// encoding:NSUTF8StringEncoding];
// NSLog(@"%@",str);
//2.开始解析数据
//a.将xml数据转换成树;
GdataxMLDocument * document = [[GdataxMLDocument alloc]
initWithData:data options:0 error:nil];
//b.获取根节点;
GdataxMLElement *rootElement = [document rootElement];
//===================使用xpath快速获取节点(前提:先获取根节点)=================
GdataxMLElement *element = [rootElement
nodesForXPath:@"books/book[1]/name" error:nil][0];
NSString *name2 = element.stringValue;
NSLog(@"===%@===",name2);
//===================逐个遍历节点知道获取需要的节点===========
//c.根据节点名字获取子节点,返回值为数组,因为一个节点下可能有多个子节点
//c.获取books节点
GdataxMLElement *booksElement = [rootElement
elementsForName:@"books"][0];
//d.获取第一个book节点;
GdataxMLElement *bookElement = [booksElement
elementsForName:@"book"][0];
//e.获取名字节点;
GdataxMLElement *nameElement = [bookElement
elementsForName:@"name"][0];
NSString *name = nameElement.stringValue;
NSLog(@"%@",name);
//获取所有的book节点;
//数组中的数组元素全是节点;
NSArray *bookArray = [booksElement elementsForName:@"book"];
for (GdataxMLElement *tBookElement in bookArray) {
NSString * ID = [tBookElement
attributeForName:@"id"].stringValue;
NSString *language = [tBookElement
attributeForName:@"language"].stringValue;
NSLog(@"id:%@ lg:%@",ID,language);
}
}
return 0;
}
原文链接:https://www.f2er.com/xml/295383.html