iOS开发之XML解析代码
//1.加载和解析XML文件 NSString *path = [[NSBundle mainBundle] pathForResource:@"xml.txt" ofType:nil]; NSData *data = [[NSData alloc] initWithContentsOfFile:path]; // GDataXMLDocument 表示XML文档对象 // initWithData 使用NSData初始化, 就是解析 GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil]; //2.获取指定结点 XPath //CityName路径: /root/systemConfig/CityName NSArray *array = [doc nodesForXPath:@"/root/systemConfig/CityName" error:nil]; //CityName GDataXMLElement *element = [array firstObject]; NSLog(@"name=%@ value=%@",element.name,element.stringValue); //3.获取指定结点的属性 NSArray *items = [doc nodesForXPath:@"/root/systemConfig/ComeChannel/Item" error:nil]; GDataXMLElement *item = [items firstObject]; //获取属性, 属性使用GDataXMLElement表示 for(GDataXMLElement *attr in item.attributes) { NSLog(@"a-name=%@ avalue=%@",attr.name,attr.stringValue); } //4.获取所有指定名字的结点(不管位置) //XPath语法: //Item NSArray *allItem = [doc nodesForXPath:@"//Item" error:nil]; for (GDataXMLElement *e in allItem) { NSLog(@"name = %@",e.name); } //5.获取所有指定名字的属性(不管哪个结点的) //XPath语法: //@value NSArray *allValue = [doc nodesForXPath:@"//@value" error:nil]; for (GDataXMLElement *e in allValue) { NSLog(@"value = %@",e.stringValue); } //6.逐层遍历XML文件 //获取根节点 GDataXMLElement *root = doc.rootElement; //获取子节点 //root.children //获取子节点个数 //root.childCount //获取指定名字的子节点 //root elementsForName:<#(NSString *)#> }
效果图:
时间: 2024-10-09 13:52:22