IOS中XML解析之NSXMLParser
NSXMLParser解析XML数据 用法如下: 一、首先,必须继承NSXMLParserDelegate协议 @interface ViewController : UIViewController<NSXMLParserDelegate> 二、设置XML数据,并初始化NSXMLParser: 1、从本地XML文件中读取数据 NSString *strPathXml = [[NSBundle mainBundle] pathForResource:@"group" ofType:@"xml"]; NSData *xmlData = [[NSData alloc] initWithContentsOfFile:strPathXml]; NSXMLParser *parserXML = [[NSXMLParser alloc] initWithData:xmlData]; [parser setShouldProcessNamespaces:NO]; [parser setShouldReportNamespacePrefixes:NO]; [parser setShouldResolveExternalEntities:NO]; [parser setDelegate:self]; [parser parse]; [parser release]; 2、从接口Java Servlet中获取数据 NSString *nstrYwKPIUrl = [[NSString alloc]initWithFormat:@"%@?citys=%@&startTime=%@&endTime=%@&indexNames=%@",YWKPIURL,city,startTime,endTime,zbz]; //Servlet访问地址与传递参数 NSString *encodedURL = [nstrYwKPIUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //对Servlet访问地址进行编码 NSLog(@"encodedURL is %@",encodedURL); NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:encodedURL ]]; [parser setShouldProcessNamespaces:NO]; [parser setShouldReportNamespacePrefixes:NO]; [parser setShouldResolveExternalEntities:NO]; parser.delegate = self; [parser parse]; [parser release]; 三、解析XML数据 1、遍例xml的节点,执行以下代理方法 -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { xmlelement = [[NSString alloc]initWithString:elementName]; //xmlelement为XML元素节点(xmlelement为字符串变量,是在.h文件中定义的。) } 2、当xml节点有值时,则执行以下代理方法 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if ([xmlelement isEqualToString:@"START_TIME"]) { [ywKPI.times addObject:[string substringToIndex:10]]; } //START_TIME XML文件内容节点,ywKPI.times 数组对象,string xml文件START_TIME 节点值。 以下类似。 if ([xmlelement isEqualToString:@"REGION_USERLABEL"]) { [ywKPI.citys addObject:string]; } if ([xmlelement isEqualToString:@"BHTIME_CS"]) { [ywKPI.dlymss addObject:string]; } if ([xmlelement isEqualToString:@"BHTIME_PS"]) { [ywKPI.fzymss addObject:string]; } if ([xmlelement isEqualToString:@"GSM_NET_RATE"]) { NSString *gsmwljtl =[[NSString alloc]initWithFormat: @"%@%@",[NSString stringWithFormat:@"%.2f",[string floatValue]],@"%"]; [ywKPI.gsmwljtls addObject:gsmwljtl]; } } 3、当遇到XML节点结束标记时,执行以下代理方法 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { xmlelement = nil; //xmlelement为字符串变量,是在.h文件中定义的。 }
相关推荐
zhujiangtaotaise 2020-01-01
84407518 2012-07-16
AllenG 2013-07-07
Beatopcoder 2013-07-14
afrtooylsw 2014-05-14
让编程改变世界 2015-03-13
shqhope 2015-04-09
zoutian00 2015-05-12
87214552 2015-10-27
84407518 2016-01-25
89283517 2012-06-19
ObjectiveC 2012-06-14
huangshm 2019-01-14
86981633 2019-06-29
我的iOS王者之路 2019-06-28
好好学习天天 2019-06-28