#import "ViewController.h" //导入XML解析的头文件GDataXMLNode.h #import "GDataXMLNode.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 获取xml文件的路径 NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"book" ofType:@"xml"]; //获取xml文件的二进制数据 NSData *xmlData = [NSData dataWithContentsOfFile:xmlPath]; //获取xml文件的字符串数据 NSString *xmlString = [NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:nil]; //开始解析XML数据 //创建xml解析器,通过传入xml二进制 // GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil]; //创建xml解析器,通过传入xml字符串 GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithXMLString:xmlString options:0 error:nil]; //获取根节点 GDataXMLElement *rootElement = xmlDocument.rootElement; NSLog(@"rootElement.name: %@", rootElement.name); //节点名称 //获取所有子节点 NSArray *children = rootElement.children; //遍历所有子节点 for (GDataXMLElement *childElement in children) { //子节点的名称 NSLog(@"childElement.name:%@", childElement.name); } //获取所有book节点 NSArray *books = [rootElement elementsForName:@"book"]; //遍历 for (GDataXMLElement *bookElement in books) { NSLog(@"bookElement.name: %@", bookElement.name); //取出book节点的子节点title GDataXMLElement *titleElement = [[bookElement elementsForName:@"title"] firstObject]; //取出author节点 GDataXMLElement *authorElement = [[bookElement elementsForName:@"author"] firstObject]; //取出title节点的内容 NSString *titleValue = [titleElement stringValue]; NSLog(@"titleValue:%@", titleValue); //打印title节点的内容 NSLog(@"author:%@", [authorElement stringValue]); //打印author节点的内容 //取出title节点的属性lang NSString *langString = [[titleElement attributeForName:@"lang"] stringValue]; NSLog(@"langString:%@", langString); } //通过路径获取所有的title节点 NSArray *titles = [xmlDocument nodesForXPath:@"/bookstore/book/title" error:nil]; //遍历 for (GDataXMLElement *titleElement in titles) { NSLog(@"titleElement stringValue: %@", [titleElement stringValue]); } }