iOS:OC--XML(Dom)

iOS:OC--XML(Dom)_第1张图片
XML(Dom).png
#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)viewDidLoad {
    [super viewDidLoad];
    //
    
}


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


- (IBAction)gDataForXML:(UIButton *)sender {
    //获取解析文件的路径
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"message.txt" ofType:nil];
    //2.创建接收数据的对象
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    //3.创建 GDataXML 解析文档对象,并获取 fileData 数据
    GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc]initWithData:fileData options:0 error:nil];
    //3.1:获取根节点
    GDataXMLElement *rootElement = xmlDocument.rootElement;
    NSLog(@"%@",rootElement.name);
    
    //对数组初始化
    self.dataArray = [NSMutableArray array];
    //3.2:通过根节点获取下面的子节点
    for (GDataXMLElement *i in rootElement.children) {
        //创建 model 类备用
        message *messageModel = [message new];
        //3.3 遍历获取到的子节点,将子节点中的属性转换为 model 模型对象
        for (GDataXMLElement *j in i.children) {
            [messageModel setValue:j forKey:j.name];
        }
        //将模型对象装入数组
        [self.dataArray addObject:messageModel];
    }
    [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@ %@ %@",[obj recevier],[obj content],[obj sender]);
    }];
}
@end

message.h

#import 
//model 中设置的属性,要和 xml 中的标签名字一样
@interface message : NSObject

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

@end

message.m

#import "message.h"

@implementation message

-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    
}

@end

message.txt



    
        尼古拉斯.凯奇
        不见不散
        王军
    
    
        王军
        你媳妇来了
        尼古拉斯.凯奇
    

你可能感兴趣的:(iOS:OC--XML(Dom))