码迷,mamicode.com
首页 > 其他好文 > 详细

XML网络数据解析

时间:2014-11-03 10:00:36      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   for   sp   

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 {
    
    

}

 

XML网络数据解析

标签:style   blog   http   io   color   ar   os   for   sp   

原文地址:http://www.cnblogs.com/IOS-FU/p/4070435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!