Objective-C 借助第三方库解析XML格式数据

/**

 *  XML全称可扩展标记语言(eXtensible Markup Language),被设计用来传输和存储数据。

 *  解析XML--系统自带了一个C语言的libxml2

 *

 *  OnoOC的第三方库,是对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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值