GDataXMLNode解析XML

1.注意两点,一.添加/usr/include/libxml2   二.将GDataXMLNode.m设置为MRC

 1 #import "GDataViewController.h"
 2 #import "GDataXMLNode.h"
 3 #import "Student.h"
 4 #import "Cartoon.h"
 5 @interface GDataViewController ()
 6 //数组属性
 7 @property (nonatomic,strong) NSMutableArray *stuArray;
 8 @property (nonatomic,strong) NSMutableArray *cartoonArray;
 9 @end
10 
11 @implementation GDataViewController
12 
13 - (void)viewDidLoad {
14     [super viewDidLoad];
15     // Do any additional setup after loading the view.
16 }
17 
18 - (void)didReceiveMemoryWarning {
19     [super didReceiveMemoryWarning];
20     // Dispose of any resources that can be recreated.
21 }
22 - (IBAction)didClickGDataXMLButton:(id)sender {
23     self.stuArray = [NSMutableArray array];
24     //获取XMLData
25     NSData *xmlData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"XML_stu" ofType:@"txt"]];
26     //读入整个XML,返回类型GDataXMLDocument文档
27     GDataXMLDocument *xmlDocment = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil];
28     //获取根节点
29     GDataXMLElement *rootElement = xmlDocment.rootElement;
30     //获取根节点下的所有子节点
31     NSLog(@"%@",rootElement.children);
32     for (GDataXMLElement *studentELe in rootElement.children) {
33         //创建学生对象
34         Student *stu = [[Student alloc] init];
35         //获取学生节点下子节点的值
36         for (GDataXMLElement *valueEle in studentELe.children) {
37             //KVC赋值
38             [stu setValue:valueEle.stringValue forKey:valueEle.name];
39             
40         }
41         //添加到数组
42         [self.stuArray addObject:stu];
43         NSLog(@"%@",self.stuArray);
44     }
45 }
46 - (IBAction)didClickCartoonButton:(id)sender {
47     //cartoon的数组
48     self.cartoonArray = [NSMutableArray array];
49     //获取XMLData
50     NSData *xmlData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Cartoon" ofType:@"xml"]];
51     //获取文档
52     GDataXMLDocument *xmlDocment = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil];
53     //获取根节点
54     GDataXMLElement *rootElment = xmlDocment.rootElement;
55     for (GDataXMLElement *results in rootElment.children) {
56         
57         for (GDataXMLElement *albumInfoEle in results.children) {
58             Cartoon *cartoon = [[Cartoon alloc] init];
59             for (GDataXMLElement *valueEle in albumInfoEle.children) {
60                 if ([valueEle.name isEqualToString:@"name"] || [valueEle.name isEqualToString:@"desc"]) {
61                     [cartoon setValue:valueEle.stringValue forKey:valueEle.name];
62                 }
63                 
64             }
65             [self.cartoonArray addObject:cartoon];
66             
67         }
68     }
69     //NSLog(@"%@",self.cartoonArray);
70     for (Cartoon *car in self.cartoonArray) {
71         NSLog(@"名字:%@,简介:%@",car.name,car.desc);
72     }
73 }

 

posted @ 2016-03-16 20:29  恒远也  阅读(202)  评论(0编辑  收藏  举报