XMLParser解析自定义的xml文档

/**
 *  1.创建xml文档:File-->New-->ios/other-->Empty创建一个info.xml文件
 *  2.输入学生信息
 <student year = "2015">
 <name>Vincent</name>
 <age>23</age>
 <tel>01234567890</tel>
 <score>86</score>
 </student>
 
 */



#import "ViewController.h"

@interface ViewController ()<NSXMLParserDelegate>
{
    NSString *flog;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path=[[NSBundle mainBundle]pathForResource:@"info" ofType:@"xml"];
    NSData *data=[NSData dataWithContentsOfFile:path];
    NSXMLParser *tool=[[NSXMLParser alloc]initWithData:data];
    tool.delegate=self;
    //开始解析
    [tool parse];
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

    if ([elementName isEqualToString:@"student"]) {
        NSLog(@"学生的入学年份--->%@",[attributeDict valueForKey:@"year"]);
    }
    if ([elementName isEqualToString:@"name"]) {
        flog=elementName;
    }
    if ([elementName isEqualToString:@"age"]) {
        flog=elementName;
    }
    if ([elementName isEqualToString:@"tel"]) {
        flog=elementName;
    }
    if ([elementName isEqualToString:@"score"]) {
        flog=elementName;
    }
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{


    if ([flog isEqualToString:@"name"]) {
        NSLog(@"学生的姓名--->%@",string);
    }
    if ([flog isEqualToString:@"age"]) {
        NSLog(@"学生的年龄--->%@",string);
    }
    if ([flog isEqualToString:@"tel"]) {
        NSLog(@"学生的电话--->%@",string);
    }
    if ([flog isEqualToString:@"score"]) {
        NSLog(@"学生的分数--->%@",string);
    }
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    flog=nil;
}

你可能感兴趣的:(xml,文档,ios开发,Object-C)