下载地址  http://pan.baidu.com/share/link?shareid=2902188921&uk=923776187

GDataXML和TFHpple配置是一样的(配置方式参考 http://blog.csdn.net/ryantang03/article/details/7868246)

主要封装代码

html封装

#import <Foundation/Foundation.h>
#import "TFHpple.h" @interface JSHpple : NSObject
+(id)ShareHpple;
-(NSArray *)HtmlWithData:(NSData *)data XPath:(NSString *)path;
@end #import "JSHpple.h" @implementation JSHpple +(id)ShareHpple{
static dispatch_once_t onceToken;
static JSHpple *hpple=nil;
dispatch_once(&onceToken, ^{
hpple=[[JSHpple alloc] init];
});
return hpple;
} -(NSArray *)HtmlWithData:(NSData *)data XPath:(NSString *)path{
TFHpple *happen=[[TFHpple alloc] initWithHTMLData:data];
NSArray *htmlContent=[happen searchWithXPathQuery:path];
NSMutableArray *result=[NSMutableArray arrayWithCapacity:];
if (htmlContent.count<=) {
NSLog(@"没有解析到对应的数据");
return nil;
}
for (TFHppleElement *ele in htmlContent) {
NSString *content=[self SearchElement:ele];
if (!content) {
content=@"Null";
}
[result addObject:content];
} return result; } -(NSString *)SearchElement:(TFHppleElement *)element{
NSArray *childs=[element children];
if (childs.count==) {
if ([[childs lastObject] isTextNode]) {//没有子节点
return [element text];
}
else{//有子节点
TFHppleElement *childElement=[childs lastObject];
NSString *content=[self SearchElement:childElement];
if (content) {
return content;
}
}
}
return nil;
} @end

xml  -->GDataxml的用法 (通用)

#import <Foundation/Foundation.h>
#import "GDataXMLNode.h" @interface JSDataXml : NSObject +(NSArray *)ParseXmlWithPath:(NSData *)data XPath:(NSString *)path attributes:(NSArray *)attributeArrarys;
@end #import "JSDataXml.h" @implementation JSDataXml +(NSArray *)ParseXmlWithPath:(NSData *)data XPath:(NSString *)path attributes:(NSArray *)attributeArrarys{ NSError *error=nil;
//开始解析
GDataXMLDocument *doc=[[GDataXMLDocument alloc] initWithData:data options: error:&error];
if (error) {
NSLog(@"xml解析失败-->%@",[error localizedDescription]);
return nil;
}
//得到根元素
GDataXMLElement *rootElement=[doc rootElement];
//利用xpath找元素 NSArray *Elements=[rootElement nodesForXPath:path error:&error];
if (error) {
NSLog(@"xpath有误-->%@",[error localizedDescription]);
return nil;
}
if (Elements.count<=) {
NSLog(@"没有匹配到数据");
return Elements;
} NSMutableArray *result=[NSMutableArray array];
//遍历匹配到的每个元素
for (int i=; i<Elements.count; i++) {
GDataXMLElement *element=Elements[i];
if (attributeArrarys.count>) {//如果节点有元素
NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithCapacity:];
for (int i=; i<attributeArrarys.count; i++) {
NSString *key=attributeArrarys[i];
NSString *value=[[element attributeForName:key] stringValue];
if (!value) {
value=@"NULL";
}
[dic setObject:value forKey:key]; }
[result addObject:dic];
}
else{//如果节点没有元素,默认就返回属性值
NSString *str= [element stringValue];
[result addObject:str];
} } return result;
} @end

xml 第二种封装(一个子节点没有属性)推荐使用

只适合这种xml数据格式

<?xml version="1.0" encoding="utf-8"?>
<Users>
<User id="">
<name>Ryan</name>
<age></age>
</User>
<User id="">
<name>Tang</name>
<age></age>
</User>
</Users>
@protocol UseXmlParser <NSObject>

@optional
- (void)NetWorkBackConnectID:(int)connectID BackDic:(NSMutableDictionary*)aBackDic WithNetState:(int)netState; @end @interface UseXmlParser : NSObject<NSXMLParserDelegate>
{
id aTarget;
int aConnectId; NSMutableData *parData; NSXMLParser *xmlParser; NSMutableArray *dicNameArray;
BOOL endStringElement;
NSMutableString *keyString;
NSMutableDictionary *xmlDataSource;
}
-(id)initWithParserData:(NSData*)pData target:(id)toTarget connectId:(int)bConnectId; -(void)parser; @end #import "UseXmlParser.h" @implementation UseXmlParser -(id)initWithParserData:(NSData*)pData target:(id)toTarget connectId:(int)bConnectId{
if (self = [super init]) { aTarget = toTarget;
aConnectId = bConnectId; dicNameArray = [[NSMutableArray alloc] initWithCapacity:];
keyString = [[NSMutableString alloc] initWithCapacity:];
xmlDataSource=[[NSMutableDictionary alloc] initWithCapacity:];
endStringElement = FALSE; parData = [[NSMutableData alloc] initWithData:pData]; }
return self;
}
-(void)parser{
xmlParser = [[NSXMLParser alloc] initWithData:parData];
[xmlParser setDelegate:self];
[xmlParser parse];//开始解析
[xmlParser release];
} -(NSMutableDictionary*) getDic {
NSMutableDictionary *dic=xmlDataSource;
for (int i=; i<[dicNameArray count]; i++) {
dic=[dic objectForKey:(NSString*)[dicNameArray objectAtIndex:i]];
}
return dic;
}
- (NSString*)getListElement:(NSString*)elementName From:(NSArray*)array {
NSString *temp = elementName;
for (int i=; i<; i++) {
if ([array containsObject:elementName]) {
elementName = [NSString stringWithFormat:@"%@%d", temp, i+];
}
else {
return elementName;
}
}
return nil;
}
- (id)getStringByKey:(NSString*)key {
NSArray *array = [key componentsSeparatedByString:@"/"];
NSDictionary *dic = [NSDictionary dictionary];
for (int i=; i<[array count]-; i++) {
dic = [dic objectForKey:[array objectAtIndex:i]];
}
NSString *temp = [dic objectForKey:[array objectAtIndex:[array count]-]];
if (!temp) {
temp = @"";
}
return temp;
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([dicNameArray count]>) {
NSMutableDictionary *dic = [self getDic];
elementName = [self getListElement:elementName From:[dic allKeys]]; [dic setObject:[[NSMutableDictionary alloc] init] forKey:elementName];
[dicNameArray addObject:elementName];
}
else {
[xmlDataSource setObject:[[NSMutableDictionary alloc] init] forKey:elementName];
[dicNameArray addObject:elementName];
} endStringElement = TRUE;
[keyString setString:@""];
} -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
[keyString appendString:string];
}
- (NSMutableDictionary*)getLastDic {
NSMutableDictionary *dic=xmlDataSource;
for (int i=; i<[dicNameArray count]-; i++) {
dic=[dic objectForKey:(NSString*)[dicNameArray objectAtIndex:i]];
}
return dic;
}
-(void) removeLastDic {
if ([dicNameArray count]>) {
[dicNameArray removeLastObject];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if (endStringElement) {
if (![keyString isEqualToString:@"\n"]) {
if ([keyString hasPrefix:@"\n"]) {
[keyString setString:[keyString substringFromIndex:]];
}
NSMutableDictionary *dic = [self getLastDic];
[dic setObject:[NSString stringWithString:keyString] forKey:[dicNameArray objectAtIndex:[dicNameArray count]-]];
}
} [keyString setString:@""];
endStringElement = FALSE;
[self removeLastDic]; }
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@" \nxml解析返回-->> %@",xmlDataSource);
if (aTarget && [aTarget respondsToSelector:@selector(NetWorkBackConnectID:BackDic:WithNetState:)]) {
[aTarget NetWorkBackConnectID:aConnectId BackDic:xmlDataSource WithNetState:];
}
} -(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSLog(@"--error-->%@",parseError.localizedDescription);
}
-(void)dealloc{ [dicNameArray release];
[keyString release];
[xmlDataSource release];
[super dealloc];
}
@end

三种使用方式

#import "ViewController.h"
#import "JSDataXml.h"
#import "JSHpple.h"
@interface ViewController (){
//配置GDDataXML和TFHpple是相同的。
//配置信息 http://blog.csdn.net/ryantang03/article/details/7868246
} @end @implementation ViewController #pragma mark -解析html - (IBAction)Htmlclick:(id)sender {
NSString *path=[[NSBundle mainBundle] pathForResource:@"" ofType:@"html"];
NSData *data=[[NSData alloc] initWithContentsOfFile:path];
NSArray *result= [[JSHpple ShareHpple] HtmlWithData:data XPath:@"//td"];
NSLog(@"--%@",result); } #pragma mark -解析一个节点一个属性格式的xml
- (IBAction)ParseXmlOneclick:(id)sender {
NSString *path=[[NSBundle mainBundle] pathForResource:@"" ofType:@"xml"];
NSData *data=[[[NSData alloc] initWithContentsOfFile:path] autorelease];
UseXmlParser *xmlParse=[[UseXmlParser alloc] initWithParserData:data target:self connectId:];
[xmlParse parser];
} - (void)NetWorkBackConnectID:(int)connectID BackDic:(NSMutableDictionary*)aBackDic WithNetState:(int)netState{
NSLog(@"-connectId-->%zi-->%@",connectID, aBackDic);
} #pragma mark -通用方式
- (IBAction)ParseXmlMangeclick:(id)sender {
// #pragma mark -解析xml第一种格式
[self ParseXmlMethod1];
// #pragma mark -解析xml第二种格式
[self ParseXmlMethod2];
} #pragma mark -解析xml第一种格式
-(void)ParseXmlMethod1{
NSString *path=[[NSBundle mainBundle] pathForResource:@"" ofType:@"xml"];
NSData *data=[[NSData alloc] initWithContentsOfFile:path];
NSArray *attribute=@[@"wait_count",@"max_wait_time",@"branch_name",@"branch_id"];
NSArray *result= [JSDataXml ParseXmlWithPath:data XPath:@"//item" attributes:attribute];
NSLog(@"__%@-->%zi",result,result.count);
} #pragma mark -解析xml第二种格式
-(void)ParseXmlMethod2{
NSString *path=[[NSBundle mainBundle] pathForResource:@"" ofType:@"xml"];
NSData *data=[[NSData alloc] initWithContentsOfFile:path]; NSArray *result= [JSDataXml ParseXmlWithPath:data XPath:@"//name" attributes:nil];
NSLog(@"__%@-->%zi",result,result.count);
}
@end

ios中xml和html解析(封装)的更多相关文章

  1. 2016 - 1- 23 iOS中xml解析 (!!!!!!!有坑要解决!!!!!!)

    一: iOS中xml解析的几种方式简介 1.官方原生 NSXMLParser :SAX方式解析,使用起来比较简单 2.第三方框架 libxml2 :纯C 同时支持DOM与SAX GDataXML: D ...

  2. IOS中KVO模式的解析与应用

    IOS中KVO模式的解析与应用 最近老翁在项目中多处用到了KVO,深感这种模式的好处.现总结如下: 一.概述 KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修 ...

  3. iOS中XML的相关知识

    1.什么是XML “当 XML(扩展标记语言)于 1998 年 2 月被引入软件工业界时,它给整个行业带来了一场风暴.有史以来第一次,这个世界拥有了一种用来结构化文档和数据的通用且适应性强的格式,它不 ...

  4. iOS开发——XML/JSON数据解析

    NSJSONSerialization 接下来就正式开始.苹果官方给出的解析方式是性能最优越的,虽然用起来稍显复杂. 首先我们在上面已经有了我希望得到的信息的网站的API给我们的URL,在OC中,我要 ...

  5. 【原】IOS中KVO模式的解析与应用

    最近老翁在项目中多处用到了KVO,深感这种模式的好处.现总结如下: 一.概述 KVO,即:Key-Value Observing,它提供一种机制,当指定的对象的属性被修改后,则对象就会接受到通知.简单 ...

  6. python3.x中xml.etree.ElementTree解析xml举例

    1.新建xml import xml.etree.ElementTree as ETa=ET.Element('elem')c=ET.SubElement(a,'child1')c.text=&quo ...

  7. iOS边练边学--iOS中的json数据解析

    JSON数据(NSData) -> OC对照表 {} -> NSDictionary @{} [] -> NSArray @[] "jack" -> NSS ...

  8. iOS中UITextField 使用全面解析

    //初始化textfield并设置位置及大小   UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 13 ...

  9. iOS中UITextField 使用全面解析 分类: ios技术 2015-04-10 14:37 153人阅读 评论(0) 收藏

    //初始化textfield并设置位置及大小   UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 13 ...

随机推荐

  1. sharepoint list 文档上传和删除

    最近项目需要对sharepoint 文件操作,于是自己写了一个简单的工具类分享出来: namespace Microsoft.SharePoint { using System; using Syst ...

  2. 在OneNote中快速插入当前日期和时间

    做笔记,难免有时需要记录当时的时间,记住这个快捷键会让记笔记的效率提升一点. To insert the current date and time, press Alt+Shift+F. To in ...

  3. Valid Sudoku leetcode java

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  4. js中各种跨域问题实战小结

    什么是跨域?为什么要实现跨域呢?   这是因为JavaScript出于安全方面的考虑,不允许跨域调用其他页面的对象.也就是说只能访问同一个域中的资源.我觉得这就有必要了解下javascript中的同源 ...

  5. [NL系列] RNN & LSTM 网络结构及应用

    http://www.jianshu.com/p/f3bde26febed/ 这篇是 The Unreasonable Effectiveness of Recurrent Neural Networ ...

  6. StackPanel

    StackPanel 的 HorizontalAlignment 属性和 VerticalAlignment 属性 默认情况下,这两个属性都被设置为 Stretch.

  7. Magento错误 Illegal scheme supplied, only alphanumeric characters are permitted

    1.检查表core_config_data 'web/unsecure/base_url' 和'web/secure/base_url' 的值是否是正确的链接地址 2.删除系统目录var下所有子目录及 ...

  8. 微信小程序 - async/await

    下面只是做一些介绍以及使用的原因,详情介绍还请移步博主:https://www.cnblogs.com/SamWeb/p/8417940.html regenerator-runtime下载:http ...

  9. Redhat、Centos等系统配置进行网络配置的方法

    配置文件(Redhat) /etc/sysconfig/network-scripts/* : 网卡/etc/sysconfig/network-scripts/ifcfg-eth0/etc/reso ...

  10. 这两天使用JSP开发程序,记录一些基本方法

    一.截取字符串 第一步 导入包:<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn ...