标签:xml解析 nsxmlparser
本篇以以下类型的XML为例解析:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="e0">密码错误</string>
<string name="e1">手机号不存在</string>
<string name="e2">未找到该城市</string>
<string name="e3">参数异常</string>
<string name="e4">鱼种库为空</string>
<string name="e6">文件为空</string>
<string name="e7">参数异常或为空</string>
<string name="e8">发布失败</string>
<string name="e10">token异常,请重新登录</string>
<string name="e11">钓点不存在</string>
<string name="e12">钓点id未找到</string>
<string name="e13">钓点id错误</string>
<string name="e14">收藏失败</string>
<string name="e15">已收藏</string>
<string name="e16">经纬度参数错误</string>
<string name="e18">城市不能为空</string>
<string name="e17">无更多钓点</string>
<string name="e19">插入失败</string>
<string name="e20">手机号码或验证码不正确</string>
<string name="e21">参数类型错误</string>
<string name="e22">数据写入错误</string>
</resources>
-(void)parserXMLFile
{
//打开xml,读取文件内容后关闭文件
NSString * path = [[NSBundle mainBundle] pathForResource:@"error" ofType:@"xml"];
NSFileHandle * file = [NSFileHandle fileHandleForReadingAtPath:path];
NSData * data = [file readDataToEndOfFile];
[file closeFile];
//初始化解析工具
NSXMLParser * m_parser = [[NSXMLParser alloc]initWithData:data];
//设置代理
[m_parser setDelegate:self];
//开始解析,设置解析结果flag,解析结束后会执行
BOOL flag = [m_parser parse];
if (flag) {
QLLog(@"解析成功");
}else{
QLLog(@"解析失败");
}
}
//开始解析
-(void)parserDidStartDocument:(NSXMLParser *)parser
{
dicXML = [[NSMutableDictionary alloc]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 ([elementName isEqualToString:@"string"]) {
keyCode = [attributeDict objectForKey:@"name"]; //错误码
QLLog(@"keyCode:%@",keyCode);
}
}
//遇到结束标记
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//QLLog(@"end: elementName:%@\n namespaceURI:%@\n qName:%@ \n",elementName,namespaceURI,qName);
}
//节点中有值时进入此方法
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
QLLog(@"key:%@",keyCode);
QLLog(@"value:%@",string);//错误说明
string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
if(keyCode.length&&string.length){
[dicXML setObject:string forKey:keyCode];
}
}
//解析结束
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
QLLog(@"dicData:%@",dicXML);
}
标签:xml解析 nsxmlparser
原文地址:http://blog.csdn.net/u013929312/article/details/42170263