首页 > 代码库 > iOS:处理XML文件
iOS:处理XML文件
NSXMLParser是标准库类
Book.xml
<?xml version="1.0" encoding="UTF-8"?><!--Document created by: lishujun, code-style with XmlGrid Online XML Editor, http://xmlgrid.net --><book> <!-- <summary> <author>金庸</author> <content>sfdgasidfhasdfb</content> </summary> --><chapters> <chapter name="hello">hello,world</chapter> <chapter name="lishujun"> i‘m lishujun sdfsdfs aaaasdfsdf qqqqqqqq </chapter> <chapter name="lishujun2">i‘m lishujun2</chapter></chapters></book>
XmlElement.h
#import <Foundation/Foundation.h>@interface XmlElement : NSObject@property (strong, nonatomic) NSString *elementName;@property (strong, nonatomic) NSString *text;@property (strong, nonatomic) NSDictionary *attributeDict;@end
XmlElement.m
#import "XmlElement.h"@implementation XmlElement@synthesize elementName;@synthesize text;@synthesize attributeDict;@end
BookXmlParser.h
#import <Foundation/Foundation.h>#import "XmlElement.h"@interface BookXMLParser : NSObject <NSXMLParserDelegate>{ XmlElement *_element; NSXMLParser *_parser;}-(id)initWithData:(NSData*)data;-(BOOL)parse;@end
BookXmlParser.m
#import "BookXMLParser.h"#import "XmlElement.h"@implementation BookXMLParser-(id)initWithData:(NSData*)data{ if (self) { _parser = [[NSXMLParser alloc]initWithData:data]; _parser.delegate = self; } return self;}-(BOOL)parse{ _element = nil; return [_parser parse];}-(void) parser:(NSXMLParser *)parserdidStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ [self processElement]; _element = [[XmlElement alloc]init]; _element.elementName = elementName; _element.attributeDict = attributeDict; _element.text = @"";}-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ if ([_element.text isEqualToString:@""]) { _element.text = string; //NSLog(@"Now element is %@", _element.text); }}-(void) processElement{ if (_element == nil) { return; } NSLog(@"process:"); NSLog(@"%@, %@", _element.elementName, _element.text);}
iOS:处理XML文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。