XML解析之DOM詳解及與SAX解析方法的比較


XML解析(DOM)

 

XML文件解析方法介紹

我們所用到的NSXMLParser是采用SAX方法解析

SAX(Simple API for XML)
  • 只能讀,不能修改,只能順序訪問,適合解析大型XML,解析速度快
  • 常應用於處理大量數據的XML,實現異構系統的數據訪問,實現跨平台
  • 從文檔的開始通過每一節點移動,定位一個特定的節點
DOM(Document Object Model)
  • 不僅能讀,還能修改,而且能夠實現隨機訪問,缺點是解析速度慢,適合解析小型文檔
  • 一般應用與小型的配置XML,方便操作
  • 為載入到內存的文檔節點建立類型描述,呈現可橫向移動、潛在巨大的樹型結構
  • 在內存中生成節點樹操作代價昂貴

 NSXMLParser解析

1.創建NSXMLParser實例,並傳入從服務器接收的XML數據
 
2.定義解析器代理
 
3.解析器解析
 
4.通過解析代理方法完成XML數據的解析
 
使用XML解析文檔時使用協議<NSXMLParserDelegate>,實現它的代理方法

 1. 開始解析某個元素,會遍歷整個XML,識別元素節點名稱

- (void)parser:didStartElement:namespaceURI:qualifiedName:attributes:

 2. 文本節點,得到文本節點里存儲的信息數據,對於大數據可能會接收多次!為了節約內存開銷

- (void)parser:foundCharacters:

 3. 結束某個節點,存儲從parser:foundCharacters:方法中獲取到的信息

- (void)parser:didEndElement:namespaceURI:qualifiedName:

注意:在解析過程中,上述三個方法會不停的重復執行,直到遍歷完成為止

 4. 開始解析XML文檔

- (void)parserDidStartDocument:

 5. 解析XML文檔結束

- (void)parserDidEndDocument:

 6. 解析出錯

- (void)parser:parseErrorOccurred:
 
在XMLParser解析過程中,還需要實現NSXMLParserDelegate代理方法

 

如果一個XML文件中包含多個對象在解析過程中,為了能夠正確解析中文檔中的數據,需要注意一下幾點:

 

1.當前解析出得是對象還是元素值?

 

如果是對象,需要判斷當前對象時第幾個,是第一個對象,還是第二、第三……,如果是第N個,需要將第N-1的對象值取出保存。

 

如果是元素值,需要將解析出得數據,賦值給對應於對象的某個屬性。

 

2.在解析過程中,每次讀取的是一個字符,所有必須實現字符串的拼接過程,將解析出字符進行組合。用來判斷當前解析出得是對象,還是元素名。或元素值。
 

XML(DOM)具體步驟

1.在github上下載GDataXMLNode

2.配置第三方

3.使用GDataXMLNode解析XML數據

- 下載大家應該都會把,不用我教,直接來第二步

點擊工程名字,然后如下圖所示添加代碼,然后我們的第三方庫就可以使用了

 

 

 

第三步:進行XML解析數據-這兒直接上代碼,注釋也挺詳細的,相信你們都可以看懂

viewCOntroller

  1 //
  2 //  ViewController.m
  3 //  XML(DOM解析)
  4 //
  5 //  Created by ma c on 16/3/19.
  6 //  Copyright (c) 2016年 姬凱鵬. All rights reserved.
  7 //
  8 
  9 #import "ViewController.h"
 10 #import "JKPTrainInfo.h"
 11 #import "GDataXMLNode.h"
 12 @interface ViewController ()<UITableViewDataSource>
 13 
 14 @property (nonatomic, strong) NSMutableArray * dataList;
 15 
 16 @property (nonatomic,strong) UITableView *tableView;
 17 
 18 @end
 19 
 20 @implementation ViewController
 21 
 22 - (void)viewDidLoad {
 23     [super viewDidLoad];
 24     // Do any additional setup after loading the view, typically from a nib.
 25     
 26     [self initUI];
 27     
 28     [self loadData];
 29 }
 30 
 31 
 32 #pragma mark -getter and setter methods
 33 
 34 - (NSMutableArray *)dataList {
 35     
 36     if (!_dataList) {
 37         _dataList = [NSMutableArray array];
 38     }
 39     return _dataList;
 40 }
 41 
 42 -(UITableView *)tableView
 43 {
 44     if (!_tableView) {
 45         
 46         _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
 47         
 48         _tableView.dataSource = self;
 49     }
 50     return _tableView;
 51 }
 52 
 53 #pragma mark - UITableView dataSource
 54 
 55 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 56     
 57     return self.dataList.count;
 58 }
 59 
 60 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 61     
 62     static NSString * identifiter = @"cellID";
 63     
 64     UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifiter];
 65     
 66     if (!cell) {
 67         
 68         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifiter];
 69     }
 70     JKPTrainInfo *JkpInfo = self.dataList[indexPath.row];
 71     
 72     cell.textLabel.text = JkpInfo.trainStation;
 73     
 74     cell.detailTextLabel.text = JkpInfo.arriveTime;
 75     
 76     return cell;
 77 }
 78 
 79 
 80 #pragma mark - event handle methods
 81 // 載入數據
 82 - (void)loadData
 83 {
 84     NSURL *url = [NSURL URLWithString:@"http://192.168.1.68/train.xml"];
 85     
 86     NSURLRequest *requst = [NSURLRequest requestWithURL:url];
 87     
 88     [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
 89         
 90         //根據數據生成xml解析文檔
 91         GDataXMLDocument *gData = [[GDataXMLDocument alloc]initWithData:data error:nil];
 92         //獲取xml根節點下所有子節點
 93         for (GDataXMLElement *element in gData.rootElement.children) {
 94             
 95             //獲取子節點下的孫子節點
 96             for (GDataXMLElement * trainInfo in element.children) {
 97                 
 98                 //創建模型
 99                 JKPTrainInfo *info = [[JKPTrainInfo alloc]init];
100                 
101                 // 經檢測 stringValue是數據 name是節點的名字  GDataXMLElement是節點下的數據部分
102     
103                 //即這個<trainStation>上海南(車次:T81\T80)</trainStation>
104                 for (GDataXMLElement *note in trainInfo.children) {
105                     
106                     [info setValue:note.stringValue forKey:note.name];
107                     
108 //                    NSLog(@"%@",note.stringValue);
109 //                    
110 //                    NSLog(@"-----------");
111 //                    
112 //                    NSLog(@"%@",note.name);
113                 }
114                 
115                 //GDataXMLNode *att 是XML文件中這個 <trainDetailInfo info="trainDetailInfo1" rowOrder="0" hasChanges="inserted">
116                 for (GDataXMLNode *att in trainInfo.attributes ) {
117                     
118                     [info setValue:att.stringValue forKey:att.name];
119                     
120                     NSLog(@"%@",att.stringValue);
121                     
122                     NSLog(@"-----------");
123                     
124                     NSLog(@"%@",att.name);
125 
126                 }
127                 //將模型加入到數據中
128                 [self.dataList addObject:info];
129             }
130             
131         }
132         //刷新數據 一定要在異步請求里面刷新數據 不然不好使
133         [self.tableView reloadData];
134 
135     }];
136 }
137 
138 //載入視圖
139 - (void)initUI
140 {
141     [self.view addSubview:self.tableView];
142 }
143 - (void)didReceiveMemoryWarning {
144     [super didReceiveMemoryWarning];
145     // Dispose of any resources that can be recreated.
146 }
147 
148 @end

 

mode類

//
//  JKPTrainInfo.h
//  XML解析(SAX)練習
//
//  Created by ma c on 16/3/19.
//  Copyright (c) 2016年 姬凱鵬. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface JKPTrainInfo : NSObject
//解析數據
@property (nonatomic, copy) NSString * info;
@property (nonatomic, copy) NSString * rowOrder;
@property (nonatomic, copy) NSString * hasChanges;

@property (nonatomic, copy) NSString * trainStation;
@property (nonatomic, copy) NSString * arriveTime;
@property (nonatomic, copy) NSString * startTime;
@property (nonatomic, copy) NSString * KM;


@end

 


免責聲明!

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



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