IOS中的XML解析详解

在IOS解析XML主要有2种方法:

1、DOM

2、SAX

下面主要讲解第二种方法,使用NSXMLParser来解析一个xml

步骤1:

在ios应用程序种创建一个xml文件  test.xml


<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person>
		<name>gavin</name>
		<age>25</age>
	</person>
</persons>

2、让某一个类实NSXMLParserDelegate协议,并实现其中的方法如下:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
	tag=elementName;
	
	NSLog(@"tag is %@",tag);
	
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqualToString:@"person"]) { //NSLog(@"go+++"); NSLog(@"name is %@,age is %d",name,age); } } -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if ([tag isEqualToString:@"name"]) { name=[string copy]; }else if([tag isEqualToString:@"age"]) age=[string intValue]; tag=@""; }

3、创建NSXMLParser

-(IBAction)btnClick:(id)sender
{
	NSLog(@"go");
	NSString *path=[[NSBundle mainBundle] pathForResource:@"test" ofType:@"xml"];
	NSFileHandle *file=[NSFileHandle fileHandleForReadingAtPath:path];
	NSData *data=[file readDataToEndOfFile];
	[file closeFile];
	NSXMLParser *parse=[[NSXMLParser alloc] initWithData:data];
	parse.delegate=self;
	[data release];
	[parse parse];
}


你可能感兴趣的:(ios,xml,String,File,encoding,attributes)