NSXMLParser解析简例

前端之家收集整理的这篇文章主要介绍了NSXMLParser解析简例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本篇以以下类型的XML为例解析:

<?xml version="1.0"encoding="utf-8"?>

<resources>

<stringname="e0">密码错误</string>

"e1">手机号不存在</string>

"e2">未找到该城市</string>

"e3">参数异常</string>

"e4">鱼种库为空</string>

"e6">文件为空</string>

"e7">参数异常或为空</string>

"e8">发布失败</string>

"e10">token异常,请重新登录</string>

"e11">钓点不存在</string>

"e12">钓点id未找到</string>

"e13">错误</string>

"e14">收藏失败</string>

"e15">已收藏</string>

"e16">经纬度参数错误</string>

"e18">城市不能为空</string>

"e17">无更多钓点</string>

"e19">插入失败</string>

"e20">手机号码或验证码不正确</string>

"e21">参数类型错误</string>

"e22">数据写入错误</string>

</resources>


-(void)parserXMLFile

{

//打开xml,读取文件内容关闭文件

NSString* path= [[NSBundlemainBundle]pathForResource:@"error"ofType@"xml"];

NSFileHandle* file = [fileHandleForReadingAtPath:path];

NSData* data = [filereadDataToEndOfFile];

[filecloseFile];

//初始化解析工具

NSXMLParser* m_parser = [[NSXMLParseralloc]initWithData:data];

//设置代理

[m_parsersetDelegate:self];

//开始解析,设置解析结果flag,解析结束后会执行

BOOLflag = [m_parserparse];

if(flag) {

QLLog(@"解析成功");

}else{

解析失败");

}

}

//开始解析

-(void)parserDidStartDocument:(NSXMLParser*)parser

{

dicXML= [[NSMutableDictionaryalloc]initWithCapacity:10];

}

//遇到开始标记

-(void)parser:(NSXMLParser*)parser didStartElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qName attributes:(NSDictionary*)attributeDict

{

//QLLog(@"elementName:%@\n namespaceURI:%@\n qName:%@ \n attributeDic:%@",elementName,namespaceURI,qName,attributeDict);

if([elementNameisEqualToString:@"string"]) {

keyCode= [attributeDictobjectForKey:@"name"];//错误

QLLog(@"keyCode:%@"keyCode);

}

}

//遇到结束标记

-(NSXMLParser*)parser didEndElement:(NSString*)qName{

//QLLog(@"end:elementName:%@\n namespaceURI:%@\n qName:%@ \n",qName);

}

//节点中有值时进入此方法

-(NSXMLParser*)parser foundCharacters:(NSString*)string

{

(@"key:%@");

@"value:%@",string);错误说明

string = [stringstringByReplacingOccurrencesOfString@"\n"withString@""@" "];

if(keyCode.length&&string.length){

[dicXMLsetObject:stringforKey:keyCode];

}

}

//解析结束

-(void)parserDidEndDocument:(NSXMLParser*)parser

{

(@"dicData:%@");

}

原文链接:https://www.f2er.com/xml/297469.html

猜你在找的XML相关文章