zoukankan      html  css  js  c++  java
  • iOS中的数据解析(XML,JSON),SAX解析,DOM解析

    第三方

    SAT解析
    #import "SAXTableViewController.h"
    #import "Student.h"
    @interface SAXTableViewController ()<NSXMLParserDelegate>
    @property (nonatomic, retain) NSMutableArray *dataSourse; // 存储学生对象
    @property (nonatomic, retain) Student *stu; // 保存当前学生对象
    @property (nonatomic, copy) NSString *string; //保存当前读取到标签后的内容
    @end
    
    @implementation SAXTableViewController
    //懒加载
    - (NSMutableArray *)dataSourse
    {
        if (!_dataSourse) {
            self.dataSourse = [NSMutableArray arrayWithCapacity:1];
        }
        return [[_dataSourse retain] autorelease];
    }
    - (void)dealloc
    {
        self.dataSourse = nil;
        self.stu = nil;
        self.string = nil;
        [super dealloc];
    }
    /**
     *  解析:按照约定好(假象)的格式提取数据的过程叫做解析.数据提供方(后台)按照格式存放数据,数据提取(前端)按照格式提取数据.
     
        主流的数据结构:XML和JSON
        
     
        XML数据结构的特点:
        1.由标签组成,而且标签是成对存在,一对儿开始标签和结束标签叫做节点.
        2.节点可以有子节点和父节点,没有父节点的节点叫做根节点,没有子节点的叫做叶子节点.
        3.节点可以用来存储数据.
     
     XML解析原理:
     SAX解析:是一种基于事件回调的解析机制(主要通过代理方法进行解析),逐行解析,逐行读取数据,逐行写入内存,适合大数据的解析,效率比较低,系统解析就是这种方式.
     DOM解析:将数据全部读入内存,将数据读成树形结构,逐层解析,适用于小数据解析,效率比较高,第三方解析原理
     
     
     
     */
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 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.
    }
    
    
    
    #pragma mark -- 点击解析
    - (IBAction)analysisBarButtonAction:(id)sender {
        
        [self.dataSourse removeAllObjects];
        
        //1.获取要解析文件的路径
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"xml"];
        //2.根据文件路径,初始化NSData对象
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        //3.创建解析工具对象
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
        //4.设置代理,监测解析过程
        parser.delegate = self;
        parser.shouldProcessNamespaces = YES;
        //5.开始解析
        [parser parse];
        [parser release];
        
        
    }
    
    
    #pragma mark -- NSXMLParserDelegate
    //当读取到开始标签时触发
    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
       
        
        //当读取到Student 开始标签时,创建Student对象
        if ([elementName isEqualToString:@"Student"]) {
            self.stu = [[[Student alloc] init] autorelease];
            //存储节点属性对应的数据
            self.stu.position = attributeDict[@"position"];
            NSLog(@"%@",attributeDict);
            
        }
        /*
         parser  解析工具对象,elementName 标签名字,
         namespaceUR I 命名空间的唯一标示,attributedict 节点中的属性,qName标签
         NSLog(@"%@",namespaceURI);
         NSLog(@"%@",qName);
         
         */
         
        
        
        
        
        
       
        
    }
    //2.当读取到标签后的内容
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
        self.string = string; // 保存读取到的标签后的内容
    }
    //当读取到结束标签触发
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
    {
        if ([elementName isEqualToString:@"name"]) {
            self.stu.name = self.string;
        }else if ([elementName isEqualToString:@"gender"]){
            self.stu.gender = self.string;
        }else if ([elementName isEqualToString:@"age"]){
            self.stu.age = self.string;
        }else if ([elementName isEqualToString:@"phone"]){
            self.stu.phone = self.string;
        }else if ([elementName isEqualToString:@"motto"]){
            self.stu.phone = self.string;
        }else if([elementName isEqualToString:@"Student"])
        {
             [self.dataSourse addObject:self.stu];
        }
        //NSLog(@"%@",self.stu.name);
       
    }
    
    //结束标签后的内容
    - (void)parserDidEndDocument:(NSXMLParser *)parser{
        NSLog(@"Game over");
        [self.tableView reloadData];
    }
    
    
    
    
    #pragma mark - Table view data source
    //
    //- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //    return 1;
    //}
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        // Return the number of rows in the section.
        return self.dataSourse.count;
        
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"student" forIndexPath:indexPath];
        Student *data = self.dataSourse[indexPath.row];
        cell.textLabel.text = data.name;
        NSLog(@"%@",data.name);
        cell.detailTextLabel.text = data.position;
        return cell;
    }
    
    
    @end
    DOM解析
    #import "DOMTableViewController.h"
    #import "GDataXMLNode.h"
    #import "Student.h"
    
    /**
     *  GDataXMLNode.h 是由Google 提供的开源的基于DOM工作原理的XML解析方式,底层是基于C语言的libxml12 动态链接库而封装的oc的使用方式,因此效率比较高
     
        //使用该类准备工作
        1.Build Phases -- 添加动态链接库 libxml2.2.dylib
        2.Build Setting ----- Header Search Paths -- 添加路径 /user/include/libxm12
     */
    @interface DOMTableViewController ()
    
    
    @property (nonatomic, retain) NSMutableArray *dataSource; //存储所有Student对象
    @end
    
    @implementation DOMTableViewController
    
    //懒加载
    - (NSMutableArray *)dataSource
    {
        if (!_dataSource) {
            self.dataSource = [[NSMutableArray alloc] initWithCapacity:1];
        }
        return [[_dataSource retain] autorelease];
    }
    
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 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.
    }
    
    #pragma mark - Table view data source
    
    
    //左侧 点击 RootParser
    - (IBAction)btnRootParser:(id)sender {
        [self.dataSource removeAllObjects];
        //1.获取要解析的xml文件的路径
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student.xml" ofType:nil];
        //2.根据文件路径初始化 NSString 对象
        //读取文本内容
        NSString *xmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        //3.将解析内容读入到GDataXMLDocument中
        GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:xmlString options:0 error:nil];
        //4.获取根节点(GDataXMLElement节点对象,GdataXMLNode属性对象)
        GDataXMLElement *rootElement = [document rootElement];
        //5.获取根节点下所有的Student节点
        NSArray *stuElements = [rootElement elementsForName:@"m:Student"];
        //6.获取Student 节点下的字节点
        for (GDataXMLElement *stuEle in stuElements) {
            //获取Student节点下得name节点
            GDataXMLElement *nameElement = [[stuEle elementsForName:@"m:name"] firstObject];
            //获取Student节点下得gender节点
            GDataXMLElement *genderElement = [[stuEle elementsForName:@"m:gender"] firstObject];
            //获取Student节点下得age节点
            GDataXMLElement *ageElement = [[stuEle elementsForName:@"m:age"] firstObject];
            //获取Student节点下得phone节点
            GDataXMLElement *phoneElement = [[stuEle elementsForName:@"m:phone"] firstObject];
            //获取Student节点下得motto节点
            GDataXMLElement *mottoElement = [[stuEle elementsForName:@"m:motto"] firstObject];
            Student *stu = [[Student alloc] init];
            //获取节点中的数据,数据妨碍开始标签与结束标签之间
            stu.name = [nameElement stringValue];
            stu.gender = [genderElement stringValue];
            stu.age = [ageElement stringValue];
            stu.phone = [phoneElement stringValue];
            stu.motto = [mottoElement stringValue];
            //获取节点中的属性对象
            GDataXMLNode *positionNode = [stuEle attributeForName:@"position"];
            stu.position = [positionNode stringValue];
            
            //Student 类型的对象,添加到数组(数据源)
            [self.dataSource addObject:stu];
            //释放
            [stu release];
        }
        NSLog(@"%@",self.dataSource);
       [self.tableView reloadData];
        [document release];
        
    }
    
    //右侧 点击 XPath
    - (IBAction)btnXpath:(id)sender {
        //移除之前的数据源
        [self.dataSource removeAllObjects];
    
        //1.获取要解析的xml文件的路径
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student.xml" ofType:nil];
        //2.根据文件路径初始化 NSString 对象
        //读取文本内容
        NSString *xmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
        //3.将解析内容读入到GDataXMLDocument中
        GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:xmlString options:0 error:nil];
        
        //4.获取所有的叶子节点
        
        //4.1获取所有的name节点
        NSArray *nameElements = [document nodesForXPath:@"//m:name" error:nil];
        //4.2获取所有的gender节点
        NSArray *genderElements = [document nodesForXPath:@"//m:gender" error:nil];
        //4.3获取所有的age节点
        NSArray *ageElements = [document nodesForXPath:@"//m:age" error:nil];
        //4.4获取所有的phone节点
        NSArray *phoneElements = [document nodesForXPath:@"//m:phone" error:nil];
        //4.5获取所有的motto节点
        NSArray *mottoElements = [document nodesForXPath:@"//m:motto" error:nil];
        //4.6获取student节点
        NSArray *studentElements = [document nodesForXPath:@"//m:Student" error:nil];
        
        //循环次数
        int count = (int)studentElements.count;
        for (int i = 0; i < count; i++) {
            GDataXMLElement *nameEle = nameElements[i];
            GDataXMLElement *genderEle = genderElements[i];
            GDataXMLElement *ageEle = ageElements[i];
            GDataXMLElement *phoneEle = phoneElements[i];
            GDataXMLElement *mottoEle = mottoElements[i];
            
            GDataXMLNode *positionNode = [studentElements[i] attributeForName:@"position"];
            //将解析的对象,封装成Student对象
            Student *stu = [[Student alloc] init];
            stu.name = [nameEle stringValue];
            stu.gender = [genderEle stringValue];
            stu.age = [ageEle stringValue];
            stu.phone = [phoneEle stringValue];
            stu.motto = [mottoEle stringValue];
            stu.position = [positionNode stringValue];
            //添加到数组
            [self.dataSource addObject:stu];
            //释放
            [stu release];
            
        }
        
        //刷新界面
        [self.tableView reloadData];
        [document release];
    }
    
    
    
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        return self.dataSource.count;
    }
    
    
    
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
        
        Student *data = self.dataSource[indexPath.row];
        cell.textLabel.text = data.name;
    
        return cell;
    }
    
    - (void)dealloc {
        self.dataSource = nil;
        [super dealloc];
    }
    @end
    JSON解析

    #import "JSONTableViewController.h"

    #import "JSONKit.h"

    @interface JSONTableViewController ()

    @end

    @implementation JSONTableViewController

    - (void)viewDidLoad {

        [super viewDidLoad];

        

        // 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.

    }

    #pragma mark - Table view data source

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    #warning Potentially incomplete method implementation.

        // Return the number of sections.

        return 0;

    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

        // Return the number of rows in the section.

        return 0;

    }

    //左侧,系统,系统解析,效率最高

    - (IBAction)btnxitong:(id)sender {

        //1.将JSON格式的数据,解析为OC对象

        //获取文件路径

        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student.json" ofType:nil];

        //转化为 NSData 对象

        NSData *data = [NSData dataWithContentsOfFile:filePath];

        //解析

       NSMutableArray *dataArr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        NSLog(@"%@",dataArr);

        

        //2.将oc对象转化为JSON格式的数据

        NSArray *arr1 = @[@"aa", @"bb", @"dd"];

        NSDictionary *dic = @{@"key":arr1};

       NSData *data2 = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];

        

        

    }

    //右侧 第三方

    - (IBAction)btndisanfang:(id)sender {

       //将JSON 数据 转化为OC对象

        

        

        //获取文件路径

        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Student.json" ofType:nil];

        //1.转化为 NSData 对象

        NSData *data = [NSData dataWithContentsOfFile:filePath];

        

       NSArray *dataArr = [data objectFromJSONData];

        

        NSLog(@"%@",dataArr);

        

        //2.转化为 NSString 对象

        NSString *str = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

       NSArray *dataArr2 = [str objectFromJSONString];

        NSLog(@"%@=====", dataArr2);

        

        //2.将oc对象转化为JSON格式的数据

        NSArray *arr1 = @[@"aa", @"bb", @"dd"];

       NSData *jsonData1 = [arr1 JSONData];

        NSDictionary *dic = @{@"key":arr1};

       NSData *jsonData2 = [dic JSONData];

        

        

    }

    @end

    Student.h
    
    
    #import <Foundation/Foundation.h>
    
    @interface Student : NSObject
    @property (nonatomic, copy) NSString *name;
    @property (nonatomic, copy) NSString *gender;
    @property (nonatomic, copy) NSString *age;
    @property (nonatomic, copy) NSString *phone;
    @property (nonatomic, copy) NSString *motto;
    
    //节点的属性
    @property (nonatomic, copy) NSString *position;
    @end
    
    Student.m
    
    #import "Student.h"
    
    @implementation Student
    - (void)dealloc
    {
        self.name = nil;
        self.gender = nil;
        self.age = nil;
        self.phone = nil;
        self.motto = nil;
        self.position = nil;
        [super dealloc];
    }
    @end
    Student.xml
    <?xml version = "1.0" encoding = "UTF-8"?>
    <m:lanou32 xmlns:m = "www.lanou3g.com">
        <m:Student position = "iOS屌丝">
            <m:name>二豪</m:name>
            <m:gender>不详</m:gender>
            <m:age>17</m:age>
            <m:phone>38383434</m:phone>
            <m:motto>不成鸡便成鸭</m:motto>
        </m:Student>
        
        <m:Student position = "iOS调">
            <m:name>三涛</m:name>
            <m:gender>女</m:gender>
            <m:age>23</m:age>
            <m:phone>38383434</m:phone>
            <m:motto>不成鸡</m:motto>
        </m:Student>
        
        <m:Student position = "iOS思思">
            <m:name>大涛</m:name>
            <m:gender>女</m:gender>
            <m:age>24</m:age>
            <m:phone>38383434</m:phone>
            <m:motto>小鸡鸡</m:motto>
        </m:Student>
        
        <m:Student position = "iOS词穷">
            <m:name>四涛</m:name>
            <m:gender>女</m:gender>
            <m:age>24</m:age>
            <m:phone>38383434</m:phone>
            <m:motto>便成鸭</m:motto>
        </m:Student>
        
        <m:Student position = "iOS牛逼">
            <m:name>二涛</m:name>
            <m:gender>男</m:gender>
            <m:age>24</m:age>
            <m:phone>110</m:phone>
            <m:motto>座右铭</m:motto>
        </m:Student>
    </m:lanou32>
  • 相关阅读:
    HDU 5280 Senior's Array (暴力,水)
    LeetCode Intersection of Two Linked Lists (找交叉点)
    LeetCode Pascal's Triangle II (杨辉三角)
    LeetCode Lowest Common Ancestor of a Binary Search Tree (LCA最近公共祖先)
    LeetCode Binary Tree Level Order Traversal (按层收集元素)
    LeetCode Balanced Binary Tree (判断平衡树)
    LeetCode Maximum Depth of Binary Tree (求树的深度)
    LeetCode Palindrome Linked List (回文链表)
    jstl表达式的应用的条件
    dao层写展示自己需要注意的问题
  • 原文地址:https://www.cnblogs.com/wohaoxue/p/4805581.html
Copyright © 2011-2022 走看看