使用NSXMLParser解析XML
工程截图:
ViewController.h
//
// ViewController.h
// NSXMLParserDemo
//
// Created by Fox on 12-3-15.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<NSXMLParserDelegate>
- (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error;
@end
ViewController.m
//
// ViewController.m
// NSXMLParserDemo
//
// Created by Fox on 12-3-15.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
/*
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user name="fox" age="22" />
<user name="foxbabe" age="21" />
</users>
*/
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad
{
NSLog(@"viewDidLoad");
[super viewDidLoad];
NSMutableString *Strxml=[NSMutableString stringWithString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><users><user name=\"fox\" age=\"22\" /><user name=\"foxbabe\" age=\"21\" /></users>"];
NSData *data=[NSData dataWithBytes:[Strxml UTF8String] length:[Strxml length]];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; //设置XML数据
[parser setDelegate:self];
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
[parser parse];//开始解析
}
#pragma mark NSXMLParserDelegate methods
/*
*开始解析XmL
*/
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
// 解析开始时的处理
NSLog(@"parserDidStartDocument");
}
/*
*遍历xml节点
*/
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(@"didStartElement");
NSLog(@"Element:%@",elementName);
//NSLog(@"qualifiedName:%@",qName);
if (qName) {
elementName = qName;
}
if ([elementName isEqualToString:@"user"]) {
// 输出属性值
NSLog(@"Name is %@ , Age is %@", [attributeDict objectForKey:@"name"], [attributeDict objectForKey:@"age"]);
}
}
/*
*当遇到结束标记时,调用该方法
*/
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(@"didEndElement");
NSLog(@"EndElement:%@",elementName);
//NSLog(@"qualifiedName:%@",qName);
if (qName) {
elementName = qName;
}
}
/*
*当xml节点有值时,调用此函数
*/
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"foundCharacters");
NSLog(@"Value:%@",string);
}
/*
*结束XML解析
*/
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"parserDidEndDocument");
}
@end
运行结果: