數據解析之XML和JSON


1. 解析的基本的概念

 解析:從事先規定好的格式中提取數據

 解析前提:提前約定好格式,數據提供方按照格式提供數據、數據獲取方則按照格式獲取數據

 iOS開發常見的解析:XML解析、JOSN解析

2. XML數據結構

 1> 概述

  XML:Extensible markup language(可擴展標記語言),主流數據格式之一,可以用來存儲和傳輸數據。

 2> XML數據格式的功能

  • 數據交換

  • 內容管理

  • 用作配置文件

 3> XML數據格式的語法

  • 聲明

  • 節點使用一對標簽表示:起始和結束標簽。

  • 根節點是起始節點,只有一個,節點可以嵌套。

  • 節點可以有值,存儲在一對兒標簽中。

 4> XML實例

3. 使用SAX工具解析XML

 1> 概述

  Simple API for XML。基於事件驅動的解析方式,逐行解析數據。(采用協議回調機制)

 2> NSXMLParser類概述

  • NSXMLParser是iOS自帶的XML解析類,采用SAX方式解析數據

  • 解析過程由NSXMLParserDelegate協議方法回調

  • 解析過程:開始標簽 --> 取值 --> 結束標簽 --> 取值

 3> 初始化NSXMLParser

  使用NSXMLParser要先創建它,設置各種屬性,主要用到一下幾個方法:

4> NSXMLParserDelegate代理方法

5> 代碼

 

 1 #pragma mark - SAX解析xml文件
 2 - (IBAction)saxParserActionXMLDocument:(UIButton *)sender
 3 {
 4     // 1. 獲取文件路徑(獲取xcode中的文件路徑)
 5     NSString *path = [[NSBundle mainBundle] pathForResource:@"StudentInfo_XML" ofType:@"txt"];
 6     
 7     // 2. 獲取NSData類型的數據
 8     NSData *data = [NSData dataWithContentsOfFile:path];
 9     
10     NSLog(@"data = %@", data);
11     
12     // 3. 設置SAX解析,並關聯相關的xml文件
13     NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
14     
15     // 4. 設置代理
16     parser.delegate = self;
17     
18     // 5. 開始解析
19     [parser parse];
20 }
21 
22 
23 #pragma mark NSXMLParserDelegate的協議方法
24 
25 #pragma mark 1. 文檔解析
26 - (void)parserDidStartDocument:(NSXMLParser *)parser
27 {
28     
29 }
30 
31 #pragma mark 2. 開始標簽解析
32 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
33 {
34     // 根據需求的標簽獲取相關的數據
35     if ([elementName isEqualToString:@"student"]) {
36         Student *stu = [Student new];
37         
38         // 在這里不需要賦值
39         
40         // 將數據對象添加到數組中
41         [self.dataArray addObject:stu];
42     }
43     
44     // 將當前的標簽值傳給聲明的標簽屬性
45     self.currentElement = elementName;
46     
47 }
48 
49 #pragma mark 3. 解析標簽中的內容然后賦值給對象
50 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
51 {
52     // 從數組中取出相關的Student對象,每次取數組中最后的一個元素,保證值為最新的對象內容
53     Student *stu = [self.dataArray lastObject];
54     
55     // KVC
56     [stu setValue:string forKey:self.currentElement];
57     
58 }
59 
60 #pragma mark 4. 結束標簽
61 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
62 {
63     self.currentElement = nil;
64 }
65 
66 #pragma mark 5. 結束文檔解析
67 - (void)parserDidEndDocument:(NSXMLParser *)parser
68 {
69     for (Student *stu in self.dataArray) {
70         NSLog(@"name = %@, gender = %@, age = %ld", stu.name, stu.gender, stu.age);
71     }
72 }
73 
74 #pragma mark 6. 錯誤處理
75 - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
76 {
77     NSLog(@"error = %@", parseError);
78 }
79 
80 - (void)viewDidLoad {
81     [super viewDidLoad];
82     // Do any additional setup after loading the view, typically from a nib.
83 }
84 
85 - (void)didReceiveMemoryWarning {
86     [super didReceiveMemoryWarning];
87     // Dispose of any resources that can be recreated.
88 }

 

4. 使用DOM工具解析XML

 1> 概述

  DOM:Document Object Model(文檔對象模型)。DOM方式解析XML時,讀入整個XML文檔並構建一個駐留內存的樹結構(節點樹),通過遍歷樹結構可以檢索任意XML節 點,讀取它的屬性和值。而且通常情況下,可以借助XPath,直接查詢XML節點。

 2> GDataXMLNode概述

  • 采用DOM方式解析數據

  • iOS中包含一個C語言的動態鏈接庫libxml2.dylib(xcode7以后改為libxml2.tbd),解析速度比NSXMLParser快。

  • GDataXMLNode是Google提供的開源XML解析類,對libxml2.tbd進行了Objective-C的封裝,能對較小或中等的xml文檔進行讀寫操作且支持XPath語法。

 3> GDataXMLNode使用方法

    • 獲取GDataXMLNode.h/m文件,將GDataXMLNode.h/m文件添加到工程中。

編譯后會出現一個錯誤

 

這是因為沒有進行配置,朋友們不需要緊張,往下看配置。

  • 向工程中增加“libxml2.tbd”動態庫。

  • 在工程的“Build Settings”頁中找到“Header Search Path”項,添加/usr/include/libxml2”。

  • 在工程的“Build Settings”頁中找到“Other Linker Flags”項,添加“-lxml2”。

  • 進行完配置后,編譯后仍會出錯

這個錯誤是因為 非ARC文件在ARC的環境運行時 的常見錯誤,解決辦法:在 Build Phases 的 Compile Sources 中找到非ARC文件對應的 .m 文件, 將 Compiler Flags 的值設為 -fno-objc-arc

 4> GDataXMLElement類的方法

 

  5> 代碼

 

 1 #pragma mark - DOM解析xml文件
 2 - (IBAction)domParserActionXMLDocument:(UIButton *)sender
 3 {
 4     // 第一步:引入動態庫
 5     
 6     // 1. 獲取文件的路徑
 7     NSString *path = [[NSBundle mainBundle] pathForResource:@"StudentInfo_XML" ofType:@"txt"];
 8     
 9     // 2. 根據路徑獲取數據
10     NSData *data = [NSData dataWithContentsOfFile:path];
11     
12     // 3. 設置DOM解析(創建解析文檔)
13     // 第一個參數為數據
14     // 第二個參數為選擇項,是一個int型的值,一般為 0
15     GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
16     
17     // 4. 獲取根節點
18     GDataXMLElement *rootElement = document.rootElement;
19     
20     // 5. 遍歷獲取相對應的子節點
21     for (GDataXMLElement *studentElement in rootElement.children) {
22         
23         Student *stu = [Student new];
24         // 遍歷子節點的子節點
25         for (GDataXMLElement *propertyElement in studentElement.children) {
26 //            NSLog(@"%@", propertyElement);
27             
28             // 根據標簽給student賦值
29             // propertyElement.name 標簽的名字
30             // propertyElement.stringValue 標簽的值
31             
32             // kvc
33             [stu setValue:propertyElement.stringValue forKey:propertyElement.name];
34         }
35         
36         [self.dataArray addObject:stu];
37     }
38     
39     for (Student *stu in self.dataArray) {
40         
41         NSLog(@"name = %@, gender = %@, age = %ld", stu.name, stu.gender, stu.age);
42     }
43 }

 

5. JOSN數據結構

 1> 概述

  JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。JSON采用完全獨立於語言的文本格式,易於閱讀和編寫,同時也易於機器解析和生成。這些特性使JSON成為理想的數據交換語言。

 2> JSON數據結構的語法

  • JSON文件有兩種結構:

  對象:“名稱/值”對的集合。不同的語言中,它被理解為對象,記錄,結構,字典,哈希表,有鍵列表,或者關聯數組。以“{”開始,以“}”結束,是“名稱/值”對的集合。名稱和值中間用“:”隔開。多個“名稱/值”對之間用“,”隔開。

  數組: 值的有序列表。在大部分語言中,它被理解為數組。以“[”開始,以“]”結束,中間是數據。數據以“,”分隔。

  • JSON中的數據類型:字符串、數值、BOOL、對象、數組。

 3> JSON示例  

 4> JSON數據結構的功能

  • 數據交換

  • 內容管理

  • 配置文件

6. 使用Foundation進行JSON解析

 1> NSJSONSerialization

  NSJSONSerialization  里面包含了兩個方法來通過不同數據形式解析JSON數據。

 1 - (IBAction)foundationParserActionJSONDocument:(UIButton *)sender
 2 {
 3     // 1. 獲取文件的路徑
 4     NSString *path = [[NSBundle mainBundle] pathForResource:@"StudentInfo_json" ofType:@"txt"];
 5     
 6     // 2. 根據路徑獲取數據
 7     NSData *data = [NSData dataWithContentsOfFile:path];
 8     
 9     // 3. 解析
10     // 第一個參數:數據
11     // 第二個參數:選擇項,是一個int型的值,一般為 0
12     // 第三個參數:錯誤處理
13     NSArray *resultArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
14     
15     // 4. 遍歷數組,使用KVC賦值
16     for (NSDictionary *dict in resultArray) {
17         
18         Student *stu = [Student new];
19         
20         [stu setValuesForKeysWithDictionary:dict];
21         
22         [self.dataArray addObject:stu];
23     }
24     
25     for (Student *stu in self.dataArray) {
26         
27         NSLog(@"name = %@, gender = %@, age = %ld, hobby = %@", stu.name, stu.gender, stu.age, stu.hobby);
28     }
29 }

 7. 使用第三方JSONKit解析JSON數據

 1> 獲取JSONKit.h/m文件,將JSONKit.h/m文件添加到工程中。

  源碼下載地址:https://github.com/AlonerOwl/JSON-

  導入后也需要進行一次 非ARC文件在ARC的環境運行時 所需要的配置,具體見 4. 3>...

 2> 代碼

 

 1 #pragma mark - 使用JSONKit解析JSON數據
 2 - (IBAction)jsonKitParserActionJSONDocument:(id)sender
 3 {
 4     // 1. 獲取文件的路徑
 5     NSString *path = [[NSBundle mainBundle] pathForResource:@"StudentInfo_json" ofType:@"txt"];
 6     
 7     // 2. 根據路徑獲取數據
 8     NSData *data = [NSData dataWithContentsOfFile:path];
 9     
10     // 3. 解析
11     NSArray *resultArray = [data objectFromJSONData];
12     
13     // 4. 遍歷數組,使用KVC賦值
14     for (NSDictionary *dict in resultArray) {
15         
16         Student *stu = [Student new];
17         
18         [stu setValuesForKeysWithDictionary:dict];
19         
20         [self.dataArray addObject:stu];
21     }
22     
23     for (Student *stu in self.dataArray) {
24         
25         NSLog(@"name = %@, gender = %@, age = %ld, hobby = %@", stu.name, stu.gender, stu.age, stu.hobby);
26     }
27     
28 }

 

8. XML與JSON兩種數據結構的優缺點

 1> XML優缺點

  優點:


   格式統一,符合標准。


   容易與其他系統進行遠程交互, 數據共享比較方便。

  缺點:


   XML文件格式文件龐大,格式復雜, 傳輸占用帶寬。


   服務器端和客戶端都需要花費大量代碼來解析XML,不論服務器端還是客戶端都使代碼變的異常復雜和不容易維護。

   客戶端不同瀏覽器之間解析XML的方式不一致,需要重復編寫很多代碼。


   服務器端和客戶端解析XML花費資源和時間。

 2> JSON優缺點

  優點:


   數據格式比較簡單,易於讀寫,格式都是壓縮的,占用帶寬小。


   易於解析這種語言。

   支持多種語言,包括ActionScript,C,C#,ColdFusion,Java,JavaScript,Perl,PHP,Python,Ruby等語言服務器端語言,便於服務器端的解析。


   因為JSON格式能夠直接為服務器端代碼使用,大大簡化了服務器端和客戶端的代碼開發量,但是完成的任務不變,且易於維護。

  

缺點:


   沒有XML格式這么推廣的深入人心和使用廣泛,沒有XML那么通用性。


   JSON格式目前在Web Service中推廣還屬於初級階段 。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM