NSXMLParser
IPhone之NSXMLParser的使用
NSXMLParser解析xml格式的数据用法如下:
首先,NSXMLParser必须继续NSXMLParserDelegate协议
@interface XMLHelper : NSObject<NSXMLParserDelegate>
首先设置XML数据,并初始化NSXMLParser
- (void)viewDidLoad { NSMutableString *Strxml=[NSMutableStringstringWithString:@"<Body><xml1>11111111</xml1><xml2><xml3>3333333333</xml3></xml2></Body>"]; NSData *data=[NSData dataWithBytes:[Strxml UTF8String]length:[Strxml length]];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];//设置XML数据 [parser setShouldProcessNamespaces:NO]; [parser setShouldReportNamespacePrefixes:NO]; [parser setShouldResolveExternalEntities:NO];
[parser setDelegate:self]; [parser parse];
[super viewDidLoad]; } |
|
//遍例xml的节点
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString*)elementName namespaceURI:(NSString *)namespaceURIqualifiedName:(NSString *)qName attributes:(NSDictionary*)attributeDict { NSLog(@"Name:%@",elementName); } |
|
//当xml节点有值时,则进入此句
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString*)string { NSLog(@"Value:%@",string); } |
|
//当遇到结束标记时,进入此句
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString*)elementName namespaceURI:(NSString *)namespaceURIqualifiedName:(NSString *)qName {
} |