/**
* XML全称可扩展标记语言(eXtensible Markup Language),被设计用来传输和存储数据。
* 解析XML--系统自带了一个C语言的libxml2库
*
* Ono是OC的第三方库,是对libxml2进行封装
*/
//1、导入Ono第三方库
//2、添加依赖的系统库,在工程中targets -> build phases -> Link binary with libraries
// -> 添加libxml2.dylib
//3、添加头文件索引,在工程中对应的targets -> header search paths
// -> 添加/usr/include/libxml2
1.XML文档:
<?xml version="1.0" encoding="UTF-8"?><oschina>
<news>
<id>44393</id>
<title><![CDATA[微软或效仿iOS合并手机及平板Windows系统]]></title>
<url><![CDATA[http://www.oschina.net/news/44393/microsoft-combine-pad-and-phone]]></url>
...
<commentCount>14</commentCount>
<author><![CDATA[oschina]]></author>
<authorid>1</authorid>
<pubDate>2013-09-21 08:08:06</pubDate>
...
</news>
</oschina>
2.使用第三方库操作
解析xml使用的第三方库: ONOXMLDocument
底层使用系统的libxml2库, 使用的时候添加libxml2
(1)导入ONOXMLDocument库
(2)添加libxml二进制库
Build Phases ---> Link Binary 添加 libxml2.dylib
(3)设置头文件搜索路径
Build Setting--->header search Paths
双击后,点加号
添加 /usr/include/libxml2
//libxml2是系统库,需要到系统的目录下找到。
(4)添加“ONOXMLDocument.h”文件到头文件中,如工程能编译通过,则说明ONOXMLDocument添加成功
3.解析xml
#import <Foundation/Foundation.h>
#import "ONOXMLDocument.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建XML文档对象
//读取XML文档那个内容
NSData *data = [NSData dataWithContentsOfFile:@"/Users/IOS1602/Desktop/news_detail.xml"];
NSError *error = nil;
ONOXMLDocument *xmlDoc = [ONOXMLDocument XMLDocumentWithData:data error:&error];
//判断是否解析成功
if (error) {
NSLog(@"XML解析失败");
return 0;//程序结束
}
//读取XML数据
//获取XML的根节点
ONOXMLElement *rootElement = [xmlDoc rootElement];
//获取节点名称
NSString *rootTagName = rootElement.tag;
NSLog(@"%@",rootTagName);
//获取一个节点的所有子节点
NSArray *arrRootChildren = [rootElement children];
//取出第一个子节点news节点
ONOXMLElement *newsElement = arrRootChildren[0];
//找到指定标签名字的节点
NSArray *idElements = [newsElement childrenWithTag:@"id"];
//取出id节点
ONOXMLElement *idElement = idElements[0];
NSLog(@"%@",[idElement stringValue]);
/**
* 通过XPath语法查找节点
*/
//查找某个节点的所有子节点
ONOXMLElement *pathIDElement = [newsElement firstChildWithXPath:@"id"];
NSLog(@"%@",pathIDElement.stringValue);
//从根节点开始查找title节点
ONOXMLElement *titleElement = [rootElement firstChildWithXPath:@"/oschina/news/title"];
NSLog(@"%@",titleElement.stringValue);
}
return 0;
}