KissXML解析

前端之家收集整理的这篇文章主要介绍了KissXML解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_0@#import "ViewController.h" #import "DDXML.h" #import "User.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view,typically from a nib. /* xml的元素:开始标签到结束标签的部分。 */ // [NSURL URLWithString:@"http://www"]; // [NSURL fileURLWithPath:@"/Users/xxx"]; //1.读取文件内容 NSString *path = [[NSBundle mainBundle] pathForResource:@"user.xml" ofType:nil]; NSString *content = [NSString stringWithContentsOfURL:[NSURL fileURLWithPath:path] encoding:NSUTF8StringEncoding error:nil]; //2.解析 /* initWithXMLString:要解析的字符串 options:预保留参数 */ //xml解析器 DDXMLDocument *document = [[DDXMLDocument alloc] initWithXMLString:content options:0 error:nil]; //根据xpath找指定节点 NSArray *elements = [document nodesForXPath:@"/Users/User" error:nil]; //User for (DDXMLElement *userElement in elements) { //[父元素对象 elementsForName:子元素名字]; //name元素 DDXMLElement *nameElement = [userElement elementsForName:@"name"][0]; //age元素 DDXMLElement *ageElement = [userElement elementsForName:@"age"][0]; NSString *name = [nameElement stringValue]; NSString *age = [ageElement stringValue]; NSLog(@"--- %@ -- %@",name,age); } } //解析1.xml - (void)parse1XMLFile { //1.读取文件内容 NSString *path = [[NSBundle mainBundle] pathForResource:@"1.xml" ofType:nil]; NSString *content = [NSString stringWithContentsOfURL:[NSURL fileURLWithPath:path] encoding:NSUTF8StringEncoding error:nil]; //2.解析 /* initWithXMLString:要解析的字符串 options:预保留参数 */ //xml解析器 DDXMLDocument *document = [[DDXMLDocument alloc] initWithXMLString:content options:0 error:nil]; /* root/list/list/list */ //root/category/list/list/list NSArray *elements = [document nodesForXPath:@"root/category/list/list/list" error:nil]; //遍历每个list元素 for (DDXMLElement *element in elements) { //获取节点 key=value DDXMLNode *node = [element attributeForName:@"dname"]; //取属性值 NSString *name = [node stringValue]; NSLog(@"%@",name); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end

猜你在找的XML相关文章