GDataXMLDocument解析XML数据

1.base64加密的xml数据,解密处理得到xml的NSData数据,

NSData *base64Data = [[NSData alloc] initWithBase64EncodedString:value options:NSDataBase64DecodingIgnoreUnknownCharacters];
//xml字符串
NSString *  restoreString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];

2.第三方GDataXMLDocument进行xml解析
下载GDataXML第三方库,并在工程中进行设置
(1)找到“Header Search Paths”项,并添加“/usr/include/libxml2”到列表中;
(2)找到“Linking\Other Linker Flags”项,并添加“-lxml2”到列表中;

3.递归解析xml数据,最后生成OC原生对象

//解析xml数据 - wzt
-(NSMutableDictionary*)parseToOCObjectWithXMLData:(NSData*)xmlData {
    
    //使用NSData对象初始化
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData  options:0 error:nil];
    
    //获取根节点(Users)
    GDataXMLElement *rootXMLElement = [doc rootElement];
    //根节点名称
    NSString *rootElementName = [rootXMLElement name];
    
    //根节点字典
    NSMutableDictionary *rootDic = [NSMutableDictionary dictionary];
    //递归解析
    NSMutableDictionary *childDic = [self parseRootGDataXMLElement:rootXMLElement];
    [rootDic setObject:childDic forKey:rootElementName];
    
    return rootDic;
}
//递归解析xml根节点,转换成字典类型
-(NSMutableDictionary*)parseRootGDataXMLElement:(GDataXMLElement*)rootXMLElement{
    
    NSMutableDictionary *rootDic = [NSMutableDictionary dictionary];
    
    NSArray *childrenElementOfRoot = rootXMLElement.children;
    
    for (GDataXMLElement* childrenElement in childrenElementOfRoot) {
        
        NSString *childElementName = [childrenElement name];
        //获取根节点下的节点
        NSArray *subChildElementArray = [rootXMLElement elementsForName:childElementName];
        if (subChildElementArray.count==1) {
            NSArray *subsubChildElementArray = childrenElement.children;
            if (subsubChildElementArray.count==1) {
                [rootDic setObject:[childrenElement stringValue] forKey:childElementName];
            }else if (subsubChildElementArray.count>1) {
                
                NSMutableDictionary *subChildDic = [self parseRootGDataXMLElement:childrenElement];
                [rootDic setObject:subChildDic forKey:childElementName];
            }
            
        }else if (subChildElementArray.count>1) {
            
            NSMutableArray *childArray = [NSMutableArray array];
            for (GDataXMLElement* childrenElement in subChildElementArray) {
                NSMutableDictionary *childDic = [self parseRootGDataXMLElement:childrenElement];
                [childArray addObject:childDic];
            }
            [rootDic setObject:childArray forKey:childElementName];
        }
    }
    
    return rootDic;
}

你可能感兴趣的:(GDataXMLDocument解析XML数据)