XML数据解析
Posted ZhangDreamK
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML数据解析相关的知识,希望对你有一定的参考价值。
这是一篇关于XML解析的详细的Demo
里面是一些XML解析相关的方法
分两部分:
1.SAX系统解析 详细的model构建 以及解析过程 协议方法
2.Dom三方解析 两个重要的概念 ONOXMLDocument ONOXMLElement 获取节点数据
(HTTP—超文本传输协议
html—超文本标记语言
markdown—
WebService—数据格式XML
二叉树遍历
GFW——Great Fire Wall,长城防火墙,网络审查)
import “ViewController.h”
import “NewsDetailModel.h”
import < Ono.h >
@interface ViewController ()< NSXMLParserDelegate >
@property (nonatomic, strong) NSXMLParser * parser; // SAX
@property (nonatomic, strong) NewsDetailModel * detailModel; // 数据模型
@property (nonatomic, copy) NSString * nodeName; //记录当前解析的节点名称
@property (nonatomic, strong) ONOXMLDocument * onoDoc; // DOM解析方式
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation ViewController
(void)viewDidLoad
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// [self SAXDemo];
[self DOMDemo];
(void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
pragma mark - DOM
(void)DOMDemo
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(0, 0), ^
NSData * xmlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@”http://www.oschina.net/action/api/news_detail?id=44393“]];
NSLog(@”data = %@”, xmlData);
NSError * error;
// 创建Ono DOM解析文档对象
weakSelf.onoDoc = [ONOXMLDocument XMLDocumentWithData:xmlData error:&error];
// 获取DOM的根节点
ONOXMLElement * rootElement = weakSelf.onoDoc.rootElement;
NSLog(@”rootElement=%@”, rootElement.tag);
// 找单个节点
ONOXMLElement * idElement = [rootElement firstChildWithXPath:@”//news/id”];
NSLog(@”idElement=%@”, idElement.tag);
// 找到多个相同节点,需要找到节点的父节点,再通过父节点获取所有的子节点
ONOXMLElement * relativiesElement = [rootElement firstChildWithXPath:@”//news/relativies”];
NSArray * relativies = [relativiesElement childrenWithTag:@”relative”];
NSLog(@”relativies count = %lu”, relativies.count);
// 找到News节点
ONOXMLElement * newsElement = [rootElement firstChildWithTag:@”news”];
// 找到title节点
ONOXMLElement * titleElement = [newsElement firstChildWithTag:@”title”];
// 获取title节点前一个节点
ONOXMLElement * preTitleElement = titleElement.previousSibling;
// 获取title节点后一个节点
ONOXMLElement * nextTitleElement = titleElement.nextSibling;
// 创建模型,并找到相应的节点数据
weakSelf.detailModel = [[NewsDetailModel alloc] init];
weakSelf.detailModel.ID = idElement.stringValue;
weakSelf.detailModel.title = titleElement.stringValue;
// 找到body节点
ONOXMLElement * bodyElement = [newsElement firstChildWithTag:@”body”];
weakSelf.detailModel.body = bodyElement.stringValue;NSLog(@"model id = %@, title = %@, body = %@", weakSelf.detailModel.ID, weakSelf.detailModel.title, weakSelf.detailModel.body); // 回到主队列加载数据到UI上 dispatch_async(dispatch_get_main_queue(), ^ weakSelf.titleLabel.text = weakSelf.detailModel.title; // UIWebView第一种加载网页,加载已有html代码 [weakSelf.webView loadHTMLString:weakSelf.detailModel.body baseURL:nil]; );
);
pragma mark - SAX
// SAX XML解析方式
- (void)SAXDemo
__weak typeof(self) weakSelf = self;
NSURLSession * session = [NSURLSession sharedSession];
NSURLSessionDataTask * dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://www.oschina.net/action/api/news_detail?id=44393"] completionHandler:^(NSData * data, NSURLResponse * response, NSError * error)
NSLog(@"%@", data);
NSString * xmlStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", xmlStr);
// 创建NSXMLParser对象
weakSelf.parser = [[NSXMLParser alloc] initWithData:data];
// 设置委托
weakSelf.parser.delegate = weakSelf;
// 开始解析
[weakSelf.parser parse];
// 中断/结束解析
//[weakSelf.parser abortParsing];
];
[dataTask resume];
pragma mark - NSXMLParserDelegate
// 开始解析XML文档
- (void)parserDidStartDocument:(NSXMLParser *)parser
// 在该协议方法实现中创建数据模型
self.detailModel = [[NewsDetailModel alloc] init];
NSLog(@”XML文档解析开始”);
- (void)parserDidEndDocument:(NSXMLParser *)parser
NSLog(@”XML文档解析结束”);
NSLog(@”NewsDetailModel:%@ %@ %@”, self.detailModel.ID, self.detailModel.title, self.detailModel.body);
/**
* 解析节点数据相关方法
*/
/**
* 开始解析XML节点元素
*
* @param parser NSXMLParser解析类
* @param elementName 节点名称
* @param namespaceURI 命名空间URI,URL是URI的子集
* @param qName 命名空间中描述名称
* @param attributeDict 属性字典,属性的名称和值
*/
- (void)parser:(NSXMLParser )parser didStartElement:(NSString )elementName namespaceURI:(NSString )namespaceURI qualifiedName:(NSString )qName attributes:(NSDictionary *)attributeDict
NSLog(@”elementName = %@, attributeDict=%@”, elementName, attributeDict);
// 记录当前正在解析的节点
self.nodeName = elementName;
- (void)parser:(NSXMLParser )parser didEndElement:(NSString )elementName namespaceURI:(NSString )namespaceURI qualifiedName:(NSString )qName
NSLog(@”XML节点:%@解析结束”, elementName);
/**
* 解析XML节点中的文本信息
*/
// 解析节点中CDATA的数据
- (void)parser:(NSXMLParser )parser foundCDATA:(NSData )CDATABlock
NSString * cdataStr = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];
NSLog(@”CDATA: %@”, cdataStr);
// 为数据模型赋值
if ([self.nodeName isEqualToString:@”title”])
self.detailModel.title = cdataStr;
// 解析节点中普通字符数据
- (void)parser:(NSXMLParser )parser foundCharacters:(NSString )string
NSLog(@”foundCharacters:%@”, string);
if ([self.nodeName isEqualToString:@”id”])
self.detailModel.ID = string;
@end
以上是关于XML数据解析的主要内容,如果未能解决你的问题,请参考以下文章