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 *)parser didStartElement:(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); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。