首页 > 代码库 > iOS学习 - 21 系统自带解析 XML

iOS学习 - 21 系统自带解析 XML

准备工作:

new -> file -> other -> Empty ,在 Save As: 中随便起个名字后缀为 .xml

拷贝下面

<person>    <student>            <pid>1001</pid>            <name>小明</name>            <sex></sex>            <age>12</age>    </student></person>

完整代码

////  ViewController.m//  XML////  Created by CC on 16/8/29.//  Copyright © 2016年 CC. All rights reserved.//#import "ViewController.h"@interface ViewController ()<NSXMLParserDelegate>@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    [self analysis];}- (void)analysis {        NSString *filename = [[NSBundle mainBundle]pathForResource:@"File.xml" ofType:nil];    NSData *data =http://www.mamicode.com/ [[NSData alloc]initWithContentsOfFile:filename];    NSXMLParser *parset = [[NSXMLParser alloc]initWithData:data];    parset.delegate = self;    [parset parse];}//文档开始时触发,只触发一次- (void)parserDidStartDocument:(NSXMLParser *)parser {    NSLog(@"parsetStart");}//文档出错时触发- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {    if (parseError) {        NSLog(@"parseError:%@",parseError);    }}//遇到字符串开始触发- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {    NSLog(@"00000000----- %@",string);}//遇到开始标签触发- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict {    NSLog(@"arrributeDict --- %@",attributeDict);}//遇到结束标签触发- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {    NSLog(@"didEndElement ----- %@",elementName);}//遇到文档结束时触发- (void)parserDidEndDocument:(NSXMLParser *)parser {    NSLog(@"DidEndDocument");}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

 

iOS学习 - 21 系统自带解析 XML