iOS xml文件的解析方式 XMLDictionary,GDataXMLNode,NSXMLParser

来源:http://www.cnblogs.com/qianLL/archive/2016/03/25/5319744.html
-Advertisement-
Play Games

iOS9之後,預設網路請求是https,所有我們要設置一下網路安全,具體設置如下 1.第三方類庫 XMLDictionary 下載地址: https://github.com/nicklockwood/XMLDictionary 所用到的xml文件 http://www.meituan.com/ap ...


iOS9之後,預設網路請求是https,所有我們要設置一下網路安全,具體設置如下

1.第三方類庫 XMLDictionary

下載地址:

https://github.com/nicklockwood/XMLDictionary

 

所用到的xml文件

http://www.meituan.com/api/v1/divisions?mtt=1.help%2Fapi.0.0.im7eandj

效果如下:

代碼實現:

根視圖:

rootTableViewController.m文件

#import "rootTableViewController.h"
#import "XMLDictionary.h"
#import "secondViewController.h"
@interface rootTableViewController ()
@property(nonatomic,strong)NSArray *cityArr;
@end

@implementation rootTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   
    NSString *path=@"http://www.meituan.com/api/v1/divisions?mtt=1.help%2Fapi.0.0.im77fqda";
    
    NSURL *url=[NSURL URLWithString:path];
    
    
    NSData *data=[NSData dataWithContentsOfURL:url];
    
    XMLDictionaryParser *parser=[[XMLDictionaryParser alloc]init];
    NSDictionary *dic=[parser dictionaryWithData:data];
    self.cityArr=[NSArray arrayWithArray:dic[@"divisions"][@"division"]];
    
    
    
    
    
    NSLog(@"%@",self.cityArr);
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuseIdentifier"];

    self.title=@"城市列表";

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//     self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
}


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



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cityArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    
    cell.textLabel.text=self.cityArr[indexPath.row][@"name"];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    secondViewController *sec=[[secondViewController alloc]init];
    sec.location=self.cityArr[indexPath.row][@"location"];
    sec.title=self.cityArr[indexPath.row][@"name"];
    [self.navigationController pushViewController:sec animated:YES];


}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

第二個視圖:secondViewController.h

#import <UIKit/UIKit.h>

@interface secondViewController : UIViewController
@property(nonatomic,strong)NSDictionary *location;
@property(nonatomic,strong)NSString *title;

@end

secondViewController.m文件

#import "secondViewController.h"

@interface secondViewController ()
@property(nonatomic,strong)UILabel *latitudeName;
@property(nonatomic,strong)UILabel *longitudeName;
@property(nonatomic,strong)UILabel *timezoneName;
@property(nonatomic,strong)UILabel *latitude;
@property(nonatomic,strong)UILabel *longitude;
@property(nonatomic,strong)UILabel *timezone;
@end

@implementation secondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setKongjian];

    self.title=[NSString stringWithFormat:@"%@的經緯度",self.title];
    
    self.view.backgroundColor=[UIColor colorWithRed:0.148 green:1.000 blue:0.946 alpha:1.000];
    

}
-(void)setKongjian{
    self.latitudeName=[[UILabel alloc]initWithFrame:CGRectMake(100, 200, 100, 30)];
    self.latitudeName.text=@"緯度:";
    self.latitude=[[UILabel alloc]initWithFrame:CGRectMake(150, 200, 200, 30)];
    self.latitude.text=self.location[@"latitude"];
    
    
    self.longitudeName=[[UILabel alloc]initWithFrame:CGRectMake(100, 250, 100, 30)];
    self.longitudeName.text=@"經度:";
    self.longitude=[[UILabel alloc]initWithFrame:CGRectMake(150, 250, 200, 30)];
    self.longitude.text=self.location[@"longitude"];
    
    self.timezoneName=[[UILabel alloc]initWithFrame:CGRectMake(100, 300, 100, 30)];
    self.timezoneName.text=@"時區:";
    self.timezone=[[UILabel alloc]initWithFrame:CGRectMake(150, 300, 200, 30)];
    self.timezone.text=self.location[@"timezone"];
    
    
    [self.view addSubview:self.latitudeName];
    [self.view addSubview:self.longitudeName];
    [self.view addSubview:self.timezoneName];

    [self.view addSubview:self.latitude];
    [self.view addSubview:self.longitude];
    [self.view addSubview:self.timezone];

}

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

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

 

2.GDataXMLNode類庫

具體配置過程如下

 核心代碼

#import "rootTableViewController.h"
#import "GDataXMLNode.h"
#import "secondViewController.h"
@interface rootTableViewController ()
@property(nonatomic,strong)NSMutableDictionary *location;
@property(nonatomic,strong)NSMutableArray *locationArr;
@end

@implementation rootTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.locationArr=[NSMutableArray array];
//    獲取網路上的xml
    NSURL *url=[NSURL URLWithString:@"http://www.meituan.com/api/v1/divisions?mtt=1.help%2Fapi.0.0.im7envub"];
    
    NSData *data=[NSData dataWithContentsOfURL:url];
    
//   使用NSData對象初始化
    GDataXMLDocument *doc=[[GDataXMLDocument alloc]initWithData:data options:0 error:nil];
    
//    獲取根節點
    GDataXMLElement *rootElement=[doc rootElement];
    
//    獲取根節點以下的節點
    GDataXMLElement *divisions=[[rootElement elementsForName:@"divisions"] objectAtIndex:0];
    NSArray *division=[divisions elementsForName:@"division"];

//          NSLog(@"%@",division);
    for (GDataXMLElement *div in division) {
        self.location=[NSMutableDictionary dictionary];
//        獲取name的節點
        GDataXMLElement *nameElement=[[div elementsForName:@"name"] objectAtIndex:0];
        NSString *name=[nameElement stringValue];
       
        
//    獲取location 的節點
        GDataXMLElement *location=[[div elementsForName:@"location"] objectAtIndex:0];
        
//        獲取latitude 的節點
        GDataXMLElement *latitudeElement=[[location elementsForName:@"latitude"] objectAtIndex:0];
            NSString *latitude=[latitudeElement stringValue];

//       獲取longitude 的節點
        GDataXMLElement *longitudeElement=[[location elementsForName:@"longitude"] objectAtIndex:0];
        NSString *longitude=[longitudeElement stringValue];
        
//        把他們的值加到一個=字典中
        [self.location setObject:name forKey:@"name"];
        [self.location setObject:latitude forKey:@"latitude"];
        [self.location setObject:longitude forKey:@"longitude"];
        
//        把字典添加到可變集合中
        [self.locationArr addObject:self.location];
        
    }
    self.title=@"城市列表";
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuseIdentifier"];
 

}

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

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.locationArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    
    cell.textLabel.text=self.locationArr[indexPath.row][@"name"];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    secondViewController *sec=[[secondViewController alloc]init];
//    把字典傳遞到第二個頁面
    sec.location=self.locationArr[indexPath.row];
            [self.navigationController pushViewController:sec animated:YES];
   
    
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

第二個頁面類似

3.系統自帶的

核心代碼

#import "rootTableViewController.h"
#import "secondViewController.h"
@interface rootTableViewController ()<NSXMLParserDelegate>
@property(nonatomic,strong)NSMutableArray *arr;
@property(nonatomic,strong)NSMutableDictionary *dic;

@property(nonatomic,strong)NSString *str;
@end

@implementation rootTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *url=[NSURL URLWithString:@"http://www.meituan.com/api/v1/divisions?mtt=1.help%2Fapi.0.0.im7mg21x"];
    NSData *data=[NSData dataWithContentsOfURL:url];
    
    NSXMLParser *parser=[[NSXMLParser alloc]initWithData:data];
    
    parser.delegate=self;
    
    
    BOOL bol=[parser parse];
    NSLog(@"%d",bol);
    self.title=@"城市列表";
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuseIdentifier"];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

-(void)parserDidStartDocument:(NSXMLParser *)parser{
    
    NSLog(@"start");
    self.arr=[NSMutableArray array];
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
    NSLog(@"end");
    NSLog(@"%@",self.arr);
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict{
    
    if ([elementName isEqualToString:@"division"]) {
        self.dic=[NSMutableDictionary dictionary];
        
        [self.dic setDictionary:attributeDict];
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    if ([elementName isEqualToString:@"name" ]||[elementName isEqualToString:@"latitude"]||[elementName isEqualToString:@"longitude"]) {
        [self.dic setObject:self.str forKey:elementName];
    }else if ([elementName isEqualToString:@"division"]){
        [self.arr addObject:self.dic];
    }
    
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    self.str=string;
    
    
}



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

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    
    cell.textLabel.text=self.arr[indexPath.row][@"name"];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    secondViewController *sec=[[secondViewController alloc]init];
    sec.location=self.arr[indexPath.row];
    [self.navigationController pushViewController:sec animated:YES];
    
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 樣式: 佈局: layout dialog_set_pwd.xml 狀態選擇器: drawable btn_blue_selector.xml btn_white_selector.xml 引用值 values colors.xml 代碼: ...
  • 在實際開發中很多時候我們都為了控制項frame的操作焦頭爛額。 例如:我們只想要獲取view的width。 我們可以這麼操作:view.frame.size.width 有時我們想要改變view的width然而我們不能直接改變->需要三部曲。 讓人抓狂,為瞭解決這裡煩惱我們可以通過改變類別來達到理想的 ...
  • 89:~ zhangwenquan$ 89:~ zhangwenquan$ openssl OpenSSL> genrsa -out rsa_private_key.pem 1024 Generating RSA private key, 1024 bit long modulus ........ ...
  • 我想題目說的或許不是很清楚,那麼現在我詳細介紹一下這篇隨筆內容。 在外部無法改變UIVIew控制項的size。 這裡說是UIView,但是事實上,是大多數控制項而絕非僅UIView。 想要實現在外部無法改變size該怎麼做呢。 首先是重寫setFrame使其規定本身size,如下 重寫setFrame後 ...
  • 上一章講述了Android界面開發中的Widget,Service,BroadcastReceiver基本知識點,本章以一個實際案例-後臺音樂播放器解析各個知識點之間的關係。 1.功能需求 做一個Android音樂播放器 用到Service、Broadcast Receiver、Widget 使用後 ...
  • 使用AndroidStudio開發半年了,一路爬坑至今,剛由Windows轉mac一個星期。通過查些資料和自己摸索,記錄一些常用的快捷鍵,猶豫個人不喜歡改快捷鍵,所以都是原生的。特此分享給大家!歡迎補充~ 搜索、查看相關: com + O :類搜索 com + shift + O:文件搜索 com ...
  • 代碼在下麵,來自Q群.125311931 https://github.com/slodier/-QQ-/tree/master/%E7%B1%BB%E4%BC%BCQQ%E5%88%97%E8%A1%A8 ...
  • 這是從美團弄得xml文件,地區和經緯度。 你點了地區以後 , 就可以查看經緯度 ,因為筆者懶, 有現成的文本框 , 所有偷懶了。 下麵是一些枯燥的代碼了 。 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...