XML網絡數據解析

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數據解析的協議方法app

- (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 {
    
    

}
相關文章
相關標籤/搜索