Believe in your own future, will thank yourself right now Sinner Yun

Sinner_Yun

XML

 

 

XML

 

XML的设计主要是用来描述⼀些信息,并且进⾏行信息的传送,与HTML不同,HTML主要用来显示信息,而XML主要用来传递信息。

XML(eXtensible Markup Language) 可扩展标记语言,计算机之间使用这些标记理解并处理各种信息,XML⽂档可以由 XML的声明开始,XML的声明描述了当前文档是一个XML文 档。

 

xml和json对比:

json(相对于xml的数据,轻巧,传输速率高,冗余的数据少。缺点:可读性差) 

xml(冗余的数据多,优点:可读性强,扩展性强)

 

一【声明】

XML声明是在文档开头,根节点之前的,可以省略。声明中包含了整个文档的信息,比如说版本,字符编码等信息。

<?xml version=”1.0” encoding=”UTF-8” ?>

这是一个XML声明,由<?xml开始到?>结束,包含了xml的版本以及编码等信息。

 

二【节点】(元素节点)

XML⽂档主要由节点构成。节点指的是从开始标签到结束标签,最外层叫根节点

 <title>Harry Potter</title>

这是一个XML节点,节点的标题是title,节点的内容是Harry Potter。

 

三【属性】

属性是使用键值形式来描述与节点相关的一些信息。属性⼀般出现在开始标记中,不能出现在结束标记中,属性值必须加引号。一个节点不能包含多个同名属性。

<title id=”27”>Harry Potter</title> 

对这个节点添加一个属性,属性名称为id,属性值为27(属性也是节点的一种,属性节点指的就是 id=”27”)

 

四【基本值】

又叫原子值,指的是节点的内容

1,<title>Harry Potter</title>中Harry Potter就叫基本值

2,属性值也是基本值

 

五【节点关系】

每个xml只有一个根节点(最外层的节点)

父:上一级节点

子:下一级节点

兄弟:同级节点

先辈:父、父的父,父的父的父。。。

后代:子、子的子、子的子的子。。。

 

六【操作】

//进行xml数据解析的第三方库(工作中也非常实用)

#import "GDataXMLNode.h"

(需要导入一个系统框架,添加一个文件路径)

libxml2包.....Header Search Paths中添加 /usr/include/libxml2路径

 

1,普通解析方法

 

NSString *path = [[NSBundle mainBundle] pathForResource:@"xml" ofType:@"txt"];

NSData *xmlData = [NSData dataWithContentsOfFile:path];

//创建xml解析作用的容器,使用xml格式的data

    GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:nil];

 

//取到xml数据的根节点(所有的节点都是GDataXMLElement对象)

    GDataXMLElement *root = [document rootElement];

 

//取到root节点下名为books的子节点

    NSArray *booksArray =[root elementsForName:@"books"];

 

   //取到数组中的第0个books节点

    GDataXMLElement *books = [booksArray objectAtIndex:0];

 

    //取第0个books下面的book节点

    NSArray *bookArray = [books elementsForName:@"book"];

 

for (GDataXMLElement *book in bookArray) {

 

//拿到节点的属性,属性也是节点的一种

        NSArray *attr= book.attributes;

        //取到id属性的对象(第0个)

        GDataXMLElement *idAttr = [attr objectAtIndex:0];

        //打印属性的值

        NSLog(@"idValue:%@",idAttr.stringValue);

 

        NSArray *names =[book elementsForName:@"name"];

        //取到book下的name节点

        GDataXMLElement *name = [names objectAtIndex:0];

        //取到name节点的内容(<name>书名</name>)

        NSLog(@"name:%@",name.stringValue);

        //取到当前节点的名称(标题)

        NSLog(@"title:%@",name.name);

        //取到整个节点

        NSLog(@"xmlstring:%@",name.XMLString);

    }

 

 

2,xpath

//xpath语句是一种对xml文档进行查找的语言,表述的是查找节点的位置

 

NSString *snsPath = [[NSBundle mainBundle] pathForResource:@"sns" ofType:@"txt"];

   NSString *snsString = [NSString stringWithContentsOfFile:snsPath encoding:NSUTF8StringEncoding error:nil];

 

//进行xml解析的一个容器,把要解析的xml字符串放到容器中,通过容器进行后续的操作

GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithXMLString:snsString options:0 error:nil];

 

    //user在xml文档中的路径

    NSString *userPath = @"/root/user_list/user";

 

//根据xpath语句提供的节点的路径,取到相应的节点,放到数组中

    NSArray *users =[doc nodesForXPath:userPath error:nil];

 

//(所有的节点(根节点或子节点)都是GDataXMLElement类的对象)

    for (GDataXMLElement *user in users) {

        

        //users中所有节点标题为username的子节点

        NSArray *userNames = [user elementsForName:@"username"];

        GDataXMLElement *userName = [userNames objectAtIndex:0];

        

        //节点基本值

        NSLog(@"userName:%@",userName.stringValue);

    }

 

//双斜杠+节点名称,xpth语句,相对路径

    //拿到一个节点中所有名为totalcount的后代节点

    NSArray *totals = [doc nodesForXPath:@"//totalcount" error:nil];

    GDataXMLElement *totalCount = [totals objectAtIndex:0];

    NSLog(@"countValue:%@",totalCount.stringValue);

 

 

 

 

 

 

 

 

 

 

 

 

#import "ViewController.h"

#import "GDataXMLNode.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    

//    [self xml];

    [self xpath];

}

 

//使用xpath语句(代表节点路径的表达式)

- (void)xpath

{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"sns" ofType:@"txt"];

    NSData *data = [NSData dataWithContentsOfFile:path];

    GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];

    

    //使用绝对路径

    NSArray *userArr = [document nodesForXPath:@"/root/user_list/user/realname" error:nil];

    NSLog(@"userArr.count = %d",userArr.count);

    

    for (GDataXMLElement *realNameEle in userArr) {

        NSLog(@"realName = %@",realNameEle.stringValue);

    }

    

    //相对路径(所有节点名是username的节点)

    NSArray *userNameArr = [document nodesForXPath:@"//username" error:nil];

    NSLog(@"userNameArr.count = %d",userNameArr.count);

}

 

//xml数据的基本解析方式

- (void)xml

{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"xml" ofType:@"txt"];

    NSData *data = [NSData dataWithContentsOfFile:path];

    

    //使用GData进行xml解析,首先把数据放到解析器里

    GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];

    

    //找到根节点

    GDataXMLElement *rootElement = [document rootElement];

    //用字符串的方式打印节点

    NSLog(@"root = %@",rootElement.XMLString);

    

    //从某个节点中查询【子节点】,子节点允许重名,需要用数组接收

    NSArray *booksArr = [rootElement elementsForName:@"books"];

    //root里只有一个books子节点

    GDataXMLElement *booksElement = [booksArr lastObject];

    NSLog(@"books = %@",booksElement.XMLString);

    

    //查询book子节点

    NSArray *bookArr = [booksElement elementsForName:@"book"];

    NSLog(@"bookArr.count = %d",bookArr.count);

    

    for (GDataXMLElement *bookElement in bookArr) {

        //查询某个节点所有的属性

        NSArray *attributes = [bookElement attributes];

        //属性是特殊的节点

        GDataXMLElement *idElement = [attributes firstObject];

        //打印节点的基本值

        NSLog(@"id = %@",idElement.stringValue);

        

        GDataXMLElement *autherElement = [[bookElement elementsForName:@"auther"] lastObject];

        GDataXMLElement *autherNameElement = [[autherElement elementsForName:@"name"] lastObject];

        //打印节点名和节点值

        NSLog(@"%@:%@",autherNameElement.name,autherNameElement.stringValue);

    }

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

 

 

 

------------------------------------------------------------------------------------分割------------------------------------------------------------------------------------

#import "ViewController.h"

#import "GDataXMLNode.h"

#import "UIImageView+WebCache.h"

 

@interface ViewController () <UITableViewDataSource,UITableViewDelegate,NSURLConnectionDataDelegate>

 

{

    UITableView *_myTableView;

    

    NSMutableArray *_dataArr;

    

    NSMutableData *_downloadData;

}

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    _dataArr = [[NSMutableArray alloc]init];

    _downloadData = [[NSMutableData alloc]init];

    

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/rss/topfreeapplications/limit=18/xml"]];

    

    [NSURLConnection connectionWithRequest:request delegate:self];

    

    

    _myTableView = [[UITableView alloc]initWithFrame:self.view.bounds];

    _myTableView.delegate = self;

    _myTableView.dataSource = self;

    [self.view addSubview:_myTableView];

}

 

#pragma mark - tableView

 

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

{

    return _dataArr.count;

}

 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 150;

}

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"qqq"];

    if (!cell) {

        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"qqq"] autorelease];

        

        UIImageView *icon = [[UIImageView alloc]initWithFrame:CGRectMake(10, 25, 100, 100)];

        icon.tag = 1;

        [cell.contentView addSubview:icon];

        [icon release];

        

        

        UILabel *detail = [[UILabel alloc]initWithFrame:CGRectMake(120, 10, 190, 130)];

        detail.font = [UIFont systemFontOfSize:14];

        detail.numberOfLines = 0;

        detail.tag = 2;

        [cell.contentView addSubview:detail];

        [detail release];

    }

    

    UIImageView *icon = (UIImageView *)[cell.contentView viewWithTag:1];

    UILabel *detail = (UILabel *)[cell.contentView viewWithTag:2];

    

    GDataXMLElement *app = [_dataArr objectAtIndex:indexPath.row];

    

    GDataXMLElement *iconUrl = [[app elementsForName:@"im:image"] lastObject];

    [icon setImageWithURL:[NSURL URLWithString:iconUrl.stringValue]];

    

    GDataXMLElement *detailElement = [[app elementsForName:@"summary"]lastObject];

    detail.text = detailElement.stringValue;

    

    return cell;

}

 

#pragma mark - NSURLConnection

 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    _downloadData.length = 0;

}

 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [_downloadData appendData:data];

}

 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithData:_downloadData options:0 error:nil];

    

    GDataXMLElement *root = [doc rootElement];

    

    //在根节点中寻找entry子节点,结果放在数组中

    _dataArr.array = [root elementsForName:@"entry"];

    

    [_myTableView reloadData];

}

 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"%s",__func__);

}

 

- (void)dealloc

{

    [_dataArr release];

    [_downloadData release];

    [_myTableView release];

    [super dealloc];

}

 

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

 

posted on 2014-04-07 19:42  Sinner_Yun  阅读(287)  评论(0编辑  收藏  举报

导航