KissXML解析
发布时间:2020-12-16 08:54:12 所属栏目:百科 来源:网络整理
导读:#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. /*
#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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |