对于xml解析,只想说一句话,千万别用系统自带的解析器,否则,你会死的很惨!
GDataXMLParser是一个对xml具有良好操作的第三方库。解析的方法如下:
步骤: 一、下载GDataXMLParser库,把解压后Source/XMLSupport/下的两个文件:GDataXMLNode.h和GDataXMLNode.m拖到工程中。 一、加入libxml2.dylib框架。 二、设置Search Paths中Header Search Paths为/usr/include/libxml2。 三、在文件中导入头文件:GDataXMLNode.h。附件是GDataXMLNode.h和GDataXMLNode.m
test.xml
- <?xml version="1.0" encoding="utf-8"?>
- <list>
- <item itemid = 'item1'>
- <user itemchild_id = 'user1'>张三</user>
- <psw itemchild_id = 'psw1'>123</psw>
- </item>
- <item itemid = 'item2'>
- <user itemchild_id = 'user2'>李四</user>
- <psw itemchild_id = 'psw2'>456</psw>
- </item>
- </list>
解析代码:
- NSMutableData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"xml"]];
- GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil];
- if (doc) {
- NSArray *items = [doc nodesForXPath:@"//list/item" error:nil];
- for (GDataXMLElement *item in items) {
- //获得item的id
- NSLog(@"item.itemid = %@", [item attributeForName:@"itemid"].stringValue);
- NSArray *itemchildren = [item children];
- for (GDataXMLElement *itemchild in itemchildren) {
- NSLog(@"itemchild.Name = %@", itemchild.name);
- NSLog(@"itemchild.String = %@", itemchild.stringValue);
- //id
- NSLog(@"itemchild.itemchild_id = %@", [itemchild attributeForName:@"itemchild_id"].stringValue);
- }
- NSLog(@"/*******/");
- }
- }
打印结果: