废话不说,直接进入正题。
KissXML的配置和使用,请参考:http://www.jb51.cc/article/p-aupzmvfv-hm.html
直接上解析代码:
+(NSMutableArray *)xmlPaserWithData:(NSData *)xmlData andElements:(NSMutableArray *)elements andNode:(NSString *)node { /* xmlData : xml文件转换为 NSData elements : 节点中的所有元素 node : 需要解析的节点 */ NSMutableArray *xmlArray=[[NSMutableArray alloc]init]; NSMutableDictionary *xmlDictionary; //文档开始(KissXML是基于DOM的解析方式) DDXMLDocument *xmlDoc = [[DDXMLDocument alloc] initWithData:xmlData options:0 error:nil]; NSArray *nodes=[xmlDoc nodesForXPath:[NSString stringWithFormat:@"//%@",node] error:nil]; for (DDXMLElement *nod in nodes) { xmlDictionary=[[NSMutableDictionary alloc]init]; for (int i=0; i<[elements count]; i++) { DDXMLElement *element=[nod elementForName:[NSString stringWithFormat:@"%@",[elements objectAtIndex:i]]]; NSLog(@"elements is %@ and string is %@",element,[element stringValue]); if ([xmlDictionary valueForKey:[element stringValue]]!=nil) { [xmlDictionary removeObjectForKey:[element stringValue]]; } [xmlDictionary setValue:[element stringValue] forKey:[NSString stringWithFormat:@"%@",[elements objectAtIndex:i]]]; } NSLog(@"xmlDictionary is %@",xmlDictionary); [xmlArray addObject:xmlDictionary]; NSLog(@"xmlarray is %@",xmlArray); } return xmlArray; }
在以上代码,xmlData 是xml文件或流生成的NSData类型数据,elements数组包含需要解析的子节点名称,node为当前需要解析的父节点。
我们新建一个类,将上面解析方法写入,新建类名称为XMLParser .
如下XML :
<retValue> <status> <statusCode>1</statusCode> </status> <records> <record> <moduleName>PurchasePlan</moduleName> <newMessage>2</newMessage> </record> <record> <moduleName>PurchaSEOrder</moduleName> <newMessage>0</newMessage> </record> <record> <moduleName>Complaint</moduleName> <newMessage>3</newMessage> </record> <record> <moduleName>RealityCheck</moduleName> <newMessage>5</newMessage> </record> <record> <moduleName>Attention</moduleName> <newMessage>6</newMessage> </record> </records> </retValue>
调用以上新建的类XMLParser 中解析方法:
//moduleName和newMessage为我们需要获取的子节点
NSMutableArray *elements=[NSMutableArray arrayWithObjects:@"moduleName",@"newMessage",nil];
//record为 moduleName和newMessage父节点 NSMutableArray *moduleCount=[XMLParser xmlPaserWithData:xmlData andElements:elements andNode:@"record"];
调用解析方法后,获得解析后的数组moduleCount,moduleCount数组内容如下:
( { moduleName = PurchasePlan; newMessage = 2; },{ moduleName = PurchaSEOrder; newMessage = 0; },{ moduleName = Complaint; newMessage = 3; },{ moduleName = RealityCheck; newMessage = 5; },{ moduleName = Attention; newMessage = 6; } )
ok ,用的时候,直接调用数组使用即可。
原文链接:https://www.f2er.com/xml/298707.html