XML和JSON數據解析

數據解析有兩種
1.XML
2.JSON

先來介紹XML
XML有兩種解析格式
①SAX方式解析
②DOM方式解析

sax方式爲逐行解析,dom方式是一下全部加載到內存
1.sax需要設置代理,
2.還需要創建數據解析工具對象NSXMLParser,
3.實現代理中的方法。
4.最後要開啓解析。

在開始解析標籤中提取數據。

dom方式解析數據
不用設置代理
但需要用GDataXMLDocumnt對象來接受數據,用GDataSMLElement來獲取跟節點。
需要對GDataXMLDocumnt,GDataSMLElement的屬性有一定的瞭解。

DOM方式解析

1.讀取路徑
2.用NSData來接受數據
3.用NSJSONSerialization來解析數據。

#import "ViewController.h"
#import "Student.h"
#import "GDataXMLNode.h"
#import "Teacher.h"
#import "JSONKit.h"

@interface ViewController ()

{
    NSString *_currentElementName;//用來臨時接受“開始標籤”的名字
}

@property(nonatomic,retain)NSMutableArray * studentsArray;//存放所有對象

@property(nonatomic,retain)NSMutableArray * teachersArray;//存放所有老師對象


- (IBAction)didclickSAX:(UIButton *)sender;

- (IBAction)didClickDOM:(UIButton *)sender;

- (IBAction)didClickJSON:(UIButton *)sender;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark ===========使用SAX方式解析XML格式的數據(採用的是協議回調機制,來逐行解析數據,使用的系統提供的工具類:NSXMLParser)
- (IBAction)didclickSAX:(UIButton *)sender {

    //獲取文件路徑
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Students" ofType:nil];

    //2.根據文件路徑來獲取文件中的數據,並將其轉換爲NSData,

    NSData *date = [NSData dataWithContentsOfFile:filePath];

    //3.解析數據

        //①.創建解析數據的工具對象
    NSXMLParser *parser = [[NSXMLParser alloc]initWithData:date];


    //②設置代理
    parser.delegate = self;

    //③開啓解析

    [parser parse];

}


#pragma mark --------------實現NSXMLParserDelegate協議中的方法


//1.開始解析文件
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    NSLog(@"開始解析文件");
    //     NSLog(@"%s",__FUNCTION__);


    self.studentsArray = [NSMutableArray array];
}
// sent when the parser begins parsing of the document.

//2.結束解析文件
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"結束解析文件");

    for (Student *stu in _studentsArray) {
        NSLog(@"%@,%@,%@",stu.name,stu.number,stu.address);
    }

    //     NSLog(@"%s",__FUNCTION__);
}


//3.解析開始標籤
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    //用來存儲每次讀取到的標籤名,供其他方法使用
    _currentElementName = elementName;

    NSLog(@"開始解析標籤:%@",elementName);

    if ([elementName isEqualToString:@"student"]) {
        Student *stu = [[Student alloc]init];
        [_studentsArray addObject:stu];

        [stu release];
    }
}

//4.解析結束標籤
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"結束解析標籤%@",elementName);
//     NSLog(@"%s",__FUNCTION__);
    //爲了防止讀取完結束標籤,給原來的屬性名_currentElementName 的值又賦值爲空了
    _currentElementName = nil;
}

//5.去標籤後的值
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //取出最新添加到數組中的那個student對象
    Student *stu = [_studentsArray lastObject];

    [stu setValue:string forKey:_currentElementName];

    NSLog(@"取出的值%@",string);
//    NSLog(@"%s",__FUNCTION__);
}
// This returns the string of the characters encountered thus far. You may not necessarily get the longest character run. The parser reserves the right to hand these to the delegate as potentially many calls in a row to -parser:foundCharacters:

// sent when the parser has completed parsing. If this is encountered, the parse was successful.

#pragma MARK ---------使用DOM方式解析XML格式數據(會將整個xml文件讀入內存,是以樹狀的結構存放在內存中),每一個節點都會對應一個數組,存放這個節點的所有,最終我們存取的是葉子節點
- (IBAction)didClickDOM:(UIButton *)sender {
    //1 獲取xml文件路徑

    NSString *filepath = [[NSBundle mainBundle]pathForResource:@"Students" ofType:nil];

    //2 根據路徑獲取文件,將其數據裝換爲NSdate類型

    NSData *data = [NSData dataWithContentsOfFile:filepath];


    //3.解析

    NSError *error = nil;

    //①創建解析數據的工具對象,當創建並初始化完工具類對象之後,會將整個data數據讀入內存,存在工具類對象裏(xmlDocument)
    GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc]initWithData:data options:0 error:&error];
    //獲取根節點

    GDataXMLElement * rootElement = xmlDocument.rootElement;
    //給學生數組開闢空間
    _studentsArray = [NSMutableArray array];

    for (GDataXMLElement * stuElment in rootElement.children) {

        //根節點中有幾個子節點,就會相應的創建幾個學生對象

        Student *stu = [[Student alloc]init];

        for (GDataXMLElement *element in stuElment.children) {
            //獲取葉子節點中的值
            NSLog(@"%@",element.stringValue);
            //獲取標籤名
            NSLog(@"%@",element.name);

            [stu setValue:element.stringValue forKey:element.name];
        }

        [_studentsArray addObject:stu];
        [stu release];

    }

    for (Student *stu in _studentsArray) {
        NSLog(@"------%@,%@,%@",stu.name,stu.number,stu.address);
    }

#warning mark -----------獲取所有name節點的值

    NSError *err = [NSError errorWithDomain:@"meiyou" code:5 userInfo:nil];

    NSArray *nodesArray = [xmlDocument nodesForXPath:@"//name" error:nil];
    NSArray *nodesArray1 = [xmlDocument nodesForXPath:@"//number" error:nil];
    NSArray *nodesArray2  = [xmlDocument nodesForXPath:@"//address" error:nil];
    for (GDataXMLElement *element in nodesArray2) {
//        NSLog(@"%@",element.stringValue);
        NSLog(@"%@",element.stringValue);
    }

}


#pragma  mark ===========解析JSON格式的數據(NSJSONSerialization和JSONKit方式)
- (IBAction)didClickJSON:(UIButton *)sender {
    //第一種方式:NSJSONSerialization

    //1.讀取路徑
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"Teachers" ofType:nil];
    //2.讀取文件,將其轉化爲NSDate
    NSData *data = [NSData dataWithContentsOfFile:filePath];

    //3.解析
    //第二個參數是枚舉值,    NSJSONReadingMutableContainers 表示返回值(字典,數組)是可變的,
    //NSJSONReadingMutableLeaves 表示葉子節點是可變的,幾乎不用,
    //NSJSONReadingAllowFragments 表示除了當前這個方法能解析文件中包含數組和字典文件中之外,還可以解析文件中包含的其他類型。(默認是隻能解析包含字典和數組的文件)
    NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];


    self.teachersArray = [NSMutableArray array];
    NSLog(@"=-=-=-%@", array);
    //遍歷數組
    for (NSDictionary * dict in array) {
        //數組中有幾個字典,表示我要創建幾個Teacher對象

        Teacher *teacher = [[Teacher alloc]init];

        [teacher setValuesForKeysWithDictionary:dict];

        [_teachersArray addObject:teacher];
        [teacher release];
    }

    for (Teacher *teacher in _teachersArray) {
        NSLog(@"%@",teacher);
    }

#warning mark----------------JSON解析(使用JSONKit)

    NSMutableArray * array1 = [data objectFromJSONData];
    //遍歷數組

    //創建對象

#pragma mark ------
    NSDictionary *dic = @{@"key":@[@"A",@"B",@"C"]};


    //將字典轉化爲NSData類型的數據
    NSData *date1 = [dic JSONData];


    //將字典轉化爲NSString類型的數據
    NSString * dicStr = [dic JSONString];

    NSLog(@"%@",date1);
    NSLog(@"%@",dicStr);

}
@end
發佈了65 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章