IOS:OC-XML(DOM)解析

作者: 任任任任师艳 | 来源:发表于2017-06-03 07:40 被阅读0次

1.先建立一个message.txt文档,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<messages>
<message>
<receiver>美女与野兽</receiver>
<content>不见不散</content>
<sender>如花似玉</sender>
</message>
<message>
<receiver>美女与野兽</receiver>
<content>啦啦啦</content>
<sender>六一快乐</sender>
</message>

 <message>
     <receiver>彭于晏</receiver>
     <content>华晨宇</content>
     <sender>吴亦凡</sender>
 </message>

</messages>

2.Message.h中声明属性,
//model中设置的属性,要和xml中的标签名字一样
@interface Message : NSObject

@property(nonatomic,copy)NSString * receiver;
@property(nonatomic,copy)NSString * content;
@property(nonatomic,copy)NSString * sender;

3.Message.m中写一个防崩的方法
//防崩
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{

}
4.在storyboard中拖一个button控件,并关联方法
5.ViewController.m
<1>定义一个属性
//用来存储解析后的model数据
@property(nonatomic,strong)NSMutableArray * dataArray;<2>在方法中开始解析

  • (IBAction)gDataForXML:(UIButton *)sender {
    //1.获取解析文件的路径
    NSString * filepath = [[NSBundle mainBundle] pathForResource:@"message.txt" ofType:nil];
    //2.接收数据
    NSData * fileData = [NSData dataWithContentsOfFile:filepath];
    //3.创建DGataXML解析文档对象,并且获取filedata数据
    GDataXMLDocument * xmlDocument = [[GDataXMLDocument alloc] initWithData:fileData options:0 error:nil];
//3.1获取根节点
GDataXMLElement * rootElement = xmlDocument.rootElement;
NSLog(@"%@",rootElement.name);

//3.2对数组初始化
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 content]);
}];

}

相关文章

网友评论

    本文标题:IOS:OC-XML(DOM)解析

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