1.首先加载xml网址
-(void)loadXml { NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://m.kiway.cn:50/version/ddpt.xml"]]; NSURLRequest *request1 = [NSURLRequest requestWithURL:url]; NSURLResponse *response = nil; NSError *errpr = nil; //同步加载数据 NSData *data1 = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&errpr]; NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithData:data1]; [xmlparser setDelegate:self];//设置代理方法 BOOL flag = [xmlparser parse];//开始解析数据,做一个判断,成功在开始解析 if (flag) { NSLog(@"OK"); }else { NSLog(@"获取xml文件失败"); } }
2.xml数据解析的协议方法
- (void)parserDidStartDocument:(NSXMLParser *)parser { parserObjects = [[NSMutableArray alloc] init]; //每一组信息都用数组来存,最后得到的数据即在此数组中 } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict { NSArray *elementArray = [[NSArray alloc] initWithObjects:@"serverCode",@"apkUrl",nil]; if ([elementName isEqualToString:@"version"]) { //开始解析News节点 dataDict = [[NSMutableDictionary alloc] initWithCapacity:0]; //每一条信息都用字典来存储 NSLog(@"%@",dataDict); }else { //开始解析子节点 for (NSString *e in elementArray) { if ([e isEqualToString:elementName]) { self.m_strCurrentElement = elementName; self.tempString = [NSMutableString string]; break; } } } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { //填充string if (m_strCurrentElement) { [self.tempString appendString:string]; [dataDict setObject:string forKey:m_strCurrentElement]; } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { //填充dic if (m_strCurrentElement) { [dataDict setObject:self.tempString forKey:m_strCurrentElement]; self.m_strCurrentElement = nil; self.tempString = nil; } //结束解析News节点 if ([elementName isEqualToString:@"version"]) { if (dataDict) { [parserObjects addObject:dataDict]; } } } - (void)parserDidEndDocument:(NSXMLParser *)parser { }
时间: 2024-10-01 02:32:58