Senior進階 網絡之數據解析之XML解析和JSON解析的用法

Senior進階 網絡之數據解析之XML解析和JSON解析的用法

XML解析之SAX解析
首先在視圖控制器的.m文件延展中聲明下列屬性
    //存放所有的student節(jié)點
    @property (nonatomic,strong)NSMutableArray* allDataMArray;
    //將一個student轉換為字典
    @property (nonatomic,strong)NSMutableDictionary *studentMDic;
    //存儲節(jié)點中的值
    @property (nonatomic,strong) NSString *noteValueString;

//SAX解析學習
- (void)saxParser{
    //SAX解析:基于事件驅動的解析方式,逐行解析
    //第一步:獲取文件的地址
    NSString* xmlPath = [[NSBundle mainBundle] pathForResource:@"demoXML1" ofType:@"xml"];
    //獲取文件內容
    NSString* xmlString = [NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:nil];
    //字符串轉data類型
    NSData* xmlData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
    //獲取解析對象
    //參數:需要解析的文件內容
    NSXMLParser* xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
    //設置代理
    xmlParser.delegate = self;
    //開始解析,parser解析的過程為同步,當整個解析完成了,才會執(zhí)行下一行的代碼。
    BOOL isSuccess = [xmlParser parse];
    if (isSuccess) {
        NSLog(@"數據解析成功");
    }else{
        NSLog(@"數據解析失敗");
    }
    //解析的過程不結束,就不會執(zhí)行該打印
    NSLog(@"我在解析的最底下");
}

#pragma mark ---- parser 解析的代理方法
//開始解析整個文檔了
- (void)parserDidStartDocument:(NSXMLParser *)parser{
    NSLog(@"開始解析整個文檔了");

    //初始化外部的可變數組,準備存放解析好的student節(jié)點
    self.allDataMArray = [[NSMutableArray alloc] init];
}

//當碰到開始節(jié)點或者開始標簽的時候會執(zhí)行的代理方法
//第一個參數:解析對象
//第二個參數:elementName:標簽名稱  例如:<name> name就是標簽名(節(jié)點名)
//第三個參數:namespaceURI:命名空間的標識符  例如:<teacher xml:l="www.lanou3g.com">,namespaceURI就是 l
//第四個參數:qualifiedName:命名空間的值,就是上面的 www.lanou3g.com
//第五個參數:attributeDict(字典類型):標簽的屬性 例如<student position="憤青">position就是標簽的屬性 attributeDict = {position:"憤青"}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict{
    NSLog(@"碰到開始標簽----- %@",elementName);

    //當開始解析student節(jié)點的時候,說明我們要用到字典了,需要對字典進行初始化
    if ([elementName isEqualToString:@"student"]) {
        self.studentMDic = [[NSMutableDictionary alloc] init];
    }
}
//取出標簽中的值
//參數為:標簽中的值
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    NSLog(@"正在解析的標簽的值為----- %@",string);

    //將結點的內容存儲起來,以供節(jié)點解析結束時使用
    self.noteValueString = string;
}
//遇到當前正在解析的標簽的結束標簽
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    NSLog(@"%@標簽已經解析結束",elementName);

    //
    if ([elementName isEqualToString:@"name"]) {
        //說明name標簽解析結束
        [self.studentMDic setObject:self.noteValueString forKey:elementName];
    }
    if ([elementName isEqualToString:@"age"]) {
        //說明age標簽解析結束
        [self.studentMDic setObject:self.noteValueString forKey:elementName];
    }
    if ([elementName isEqualToString:@"gender"]) {
        //說明gender標簽解析結束
        [self.studentMDic setObject:self.noteValueString forKey:elementName];
    }
    if ([elementName isEqualToString:@"student"]) {
        //說明一個student已經解析完成,說明一個字典已經完整,應該將字典存放到數組中
        [self.allDataMArray addObject:self.studentMDic];
    }
}

//整個文檔解析結束
- (void)parserDidEndDocument:(NSXMLParser *)parser{
    NSLog(@"整個文檔解析結束");

    //當整個文檔解析結束,說明所有的數據我們已經拿到,可以正常使用
    NSLog(@"self.allDataMArray ---- %@",self.allDataMArray);
}
//當解析出錯的時候執(zhí)行的代理方法
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
    NSLog(@"解析出現(xiàn)錯誤 ----- %@",parseError.description);
}
XML解析之DOM解析
第一步:導入GDataXMLNode的(.h和.m)文件
第二步:根據要求配置使用方法
第三步:解析文件
    //DOM解析的學習  基于文檔驅動的解析方式
- (void)domParser{

    //需要獲取解析的源文件
    //第一步:獲取文件的地址
    NSString* xmlPath = [[NSBundle mainBundle] pathForResource:@"demoXML1" ofType:@"xml"];
    //獲取文件內容
    NSString* xmlString = [NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:nil];
    //字符串轉data類型
    NSData* xmlData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
    //DOM解析
    //第一步:將源XML轉換成樹狀結構的文檔放在內存中,以供遍歷獲取每一個節(jié)點
    GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithData:xmlData encoding:NSUTF8StringEncoding error:nil];
    //第二步:獲取根節(jié)點  相當于獲取到了students節(jié)點
    GDataXMLElement *rootElement = [xmlDocument rootElement];

    //向現(xiàn)有的文檔動態(tài)添加一個student節(jié)點
    //student節(jié)點的創(chuàng)建  相當于<student></student>
    GDataXMLElement* studentNote = [GDataXMLElement elementWithName:@"student"];

    //為student增加子節(jié)點
    GDataXMLElement* nameNote = [GDataXMLElement elementWithName:@"name" stringValue:@"ze an"];
    //添加到studentNote
    [studentNote addChild:nameNote];

    //為student增加age子節(jié)點
    GDataXMLElement *ageNote = [GDataXMLElement elementWithName:@"age"];
    ageNote.stringValue = @"22";
    //添加到studentNote節(jié)點上
    [studentNote addChild:ageNote];

    //為studentNote增加gender子節(jié)點
    GDataXMLElement *genderNote = [GDataXMLElement elementWithName:@"gender" stringValue:@"man"];
    //添加到studentNote上
    [studentNote addChild:genderNote];

    //將student節(jié)點加入到它的父節(jié)點中
    [rootElement addChild:studentNote];

    //第三步:獲取我們需要的子節(jié)點
    //參數;我們需要獲取的子節(jié)點的標簽名
    NSArray *studentMArray = [rootElement elementsForName:@"student"];
    //初始化一個可變數組,準備存放所有的student轉換成的字典
    NSMutableArray *allStudentsArray = [[NSMutableArray alloc] init];


    //第四步:遍歷studentArray
    //studentNode 對應一個student節(jié)點
    /*
        <student>
            <name></name>
            <age></age>
            <gender></gender>
        </studnet>
    */
    //第一種:
    //沒執(zhí)行一次 循環(huán)體,就相當于獲取了一個完整的student節(jié)點,結構如上
//    for (GDataXMLElement *studentNote in studentMArray) {
//        //?初始化一個字典
//        NSMutableDictionary *studentDic = [[NSMutableDictionary alloc] init];
//        //
////        NSString *name = [[[studentNote elementsForName:@"name"] firstObject] stringValue];
//        //獲取name的節(jié)點
//        GDataXMLElement* nameElement = [studentNote elementsForName:@"name"].firstObject;
//        //取出節(jié)點中的值
//        NSString *name = nameElement.stringValue;
//        //將name的值放入字典中
//        [studentDic setObject:name forKey:@"name"];
//        
//        //獲取age節(jié)點
//        GDataXMLElement* ageElement = [studentNote elementsForName:@"age"].firstObject;
//        //取出節(jié)點中的值
//        NSString *age = ageElement.stringValue;
//        //將age的值放入字典中
//        [studentDic setObject:age forKey:@"age"];
//        
//        //獲取gender節(jié)點
//        GDataXMLElement* genderElement = [studentNote elementsForName:@"gender"].firstObject;
//        //取出節(jié)點中的值
//        NSString *gender = genderElement.stringValue;
//        //將age的值放入字典中
//        [studentDic setObject:gender forKey:@"gender"];
//        
//        //將字典添加到可變數組中
//        [allStudentsArray addObject:studentDic];
//    }

    //第二種
    for (GDataXMLElement *studentNote in studentMArray) {
        //遍歷獲取student所有的子節(jié)點
        NSArray *subStudentNode = [studentNote children];
        //初始化一個可變字典
        NSMutableDictionary *studentDic = [[NSMutableDictionary alloc] init];
        //遍歷
        for (GDataXMLElement* subOfStudentNote in subStudentNode) {
            //獲取節(jié)點的名稱
            NSString *noteName = [subOfStudentNote name];
            //獲取節(jié)點的值
            NSString *noteValue = [subOfStudentNote stringValue];
            //將值添加到字典中
            [studentDic setObject:noteValue forKey:noteName];
        }
        //將字典加入到可變數組中
        [allStudentsArray addObject:studentDic];
    }


    NSLog(@"allStudentsArray ---- %@",allStudentsArray);
}
JSON解析
//JSON解析
- (void)jsonParser{
    //獲取源文件
    NSString* jsonPath = [[NSBundle mainBundle] pathForResource:@"DemoJson" ofType:@"json"];
    //
    NSString* jsonString = [NSString stringWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:nil];
    //字符串轉換為二進制類型
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    //Json解析
    NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"dic ==== %@",dic);
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容