XML 解析

//创建可变字符串来接收内容
mutableString =[[NSMutableString alloc] init];
mutableArray  =[[NSMutableArray alloc] initWithCapacity:0];
NSURL *url =[NSURL URLWithString:@""];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//初始化XML解析对象 把要解析的数据传进去
NSXMLParser *parser =[[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
//开始解析
[parser parse];


//解析开始
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    NSLog(@"解析开始");
}
//遇到开始标签
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"hero"])
    {
        model =[[HeroModel alloc] init];
    }
    [mutableString  setString:@""];
    //NSLog(@"遇到开始标签%@",elementName);
}
//遇到内容(如果内容比较大 那么会调用多次此方法  必须要用可变字符串来接收每次返回的字符)
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //NSLog(@"遇到内容%@",string);
    //保证数据完整性
    [mutableString appendString:string];
}
//遇到结束标签
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"name"])
    {
        model.name = mutableString;
    }
    if ([elementName isEqualToString:@"hero"])
    {
        [mutableArray addObject:model];
        [model release];
    }
    //NSLog(@"遇到结束标签%@",elementName);
}
//解析结束
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"解析结束");
NSLog(@"~~~~~~%d",[mutableArray count]);
}

你可能感兴趣的:(XML 解析)