美文网首页小白学编程
OC-数据解析XML(dom)(二)

OC-数据解析XML(dom)(二)

作者: 阿狸演绎 | 来源:发表于2017-06-03 18:04 被阅读0次

    XML解析2(dom):

    一次性将整个XML文档加载到内存中,适合较小的文件

    #import "ViewController.h"

    #import "GDataXMLNode.h"

    #import "Message.h"

    @interface ViewController ()

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

    //用来存储解析后的modle数据

    @property(nonatomic,strong)NSMutableArray *dataArray;

    @end

    @implementation ViewController

    -(void)gDataForXML:(UIButton *)sender{

    //第一步:首先获取解析文件的路径

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

    //第二部:创建接收数据的对象

    NSData *fileData = [NSData dataWithContentsOfFile:filePath];

    //第三步创建gDataCML解析文档对象,并且获取fileData

    GDataXMLDocument *xmlDocunment = [[GDataXMLDocument alloc]initWithData:fileData options:0 error:nil];

    //3.1获取根节点,获取子节点

    GDataXMLElement *rootElement = xmlDocunment.rootElement;

    NSLog(@"%@",rootElement.name);

    //给数组初始化

    self.dataArray = [NSMutableArray array];

    //3.2通过根节点获取下面的子节点

    for (GDataXMLElement * childrenElement in rootElement.children) {

    //创建model对象,备用

    Message *messageModel = [Message new];

    //3.3遍历获取到的子节点,将子节点中的属性转换为model模型对象

    for (GDataXMLElement *message in childrenElement.children) {

    [messageModel setValue:message forKey:message.name];

    }//4将模型对象装入数组

    [self.dataArray addObject:messageModel];

    }

    //测试

    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

    NSLog(@"%@ %@ %@",[obj receiver],[obj sender],[obj content]);

    }];

    }

    //源文件百度云:链接: https://pan.baidu.com/s/1i4LgNEP 密码: v6cy

    相关文章

      网友评论

        本文标题:OC-数据解析XML(dom)(二)

        本文链接:https://www.haomeiwen.com/subject/bsdmfxtx.html