XML 文件解析

时间:2023-12-29 20:44:08

1.XML文件

<Data>

<Movie id="1">

<title>good lucky to you</title>

<box>111</box>

<summary>This is a story</summary>

</Movie>

<Movie id="2">

<title>hello</title>

<box>99</box>

<summary>oh,yes</summary>

</Movie>

<Movie id="3">

<title>Cold</title>

<box>100</box>

<summary>I love cold weather</summary>

</Movie>

</Data>

2,解析

#import "ViewController.h"

//创建模型类

@interface DataModel : NSObject

//Data

@property(nonatomic,copy)NSNumber *id;

@property (nonatomic,copy)NSString*title;

@property (nonatomic,copy)NSString*box;

@property (nonatomic,copy)NSString*summary;

-(instancetype)initWithDict:(NSDictionary*)dict;

+(instancetype)dataWithdict:(NSDictionary*)dict;

@end

@implementation DataModel

-(instancetype)initWithDict:(NSDictionary*)dict

{

if (self=[super init]) {

[self setValuesForKeysWithDictionary:dict];

}

return self;

}

+(instancetype)dataWithdict:(NSDictionary*)dict

{

return [[self alloc]initWithDict:dict];

}

@end

@interface ViewController ()<NSXMLParserDelegate>

@property(nonatomic,strong)NSMutableArray*models;

//主要用于XML标签体中的文本的读取,很多时候标签体内的内容不是一次读取出来的,需要拼接字符串

@property(nonatomic,copy)NSMutableString*str;

@property(nonatomic,strong)DataModel*datamodel;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

[self loadDataWithUrl:@"http://127.0.0.1/struts.xml"];

}

//XML解析方法

-(void)loadDataWithUrl:(NSString*)str

{

NSURL *url=[NSURL URLWithString:str];

NSURLRequest *quest=[NSURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:15];

[NSURLConnection sendAsynchronousRequest:quest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

if (!connectionError)

{

NSHTTPURLResponse *resnse=(NSHTTPURLResponse*)response;

if (resnse.statusCode==200) {

NSXMLParser *parser=[[NSXMLParser alloc]initWithData:data];

parser.delegate=self;

//开始解析

[parser parse];

}

}

else

{

NSLog(@"请求出错:%@",connectionError);

}

}];

}

#pragma mark NSXMLParserDelegate XML文档解析五部曲

//开始解析

-(void)parserDidStartDocument:(NSXMLParser *)parser

{

NSLog(@"开始解析!!清除之前的数据");

[self.models removeAllObjects];

}

//开始查找标签元素

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

{

//elementName 记录标签的名称  attributeDict:记录标签的属

NSLog(@"开始查找标签元素:%@",elementName);

//NSLog(@"elementName:%@,namespaceURI:%@,qName:%@",elementName,namespaceURI,qName);

//排除根节点

self.str=nil;

if ([elementName isEqualToString:@"Movie"]) {

//self.str=nil;

self.datamodel=[DataModel new];

[self.models addObject:self.datamodel];

[attributeDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

[self.datamodel setValue:obj forKey:key];

}];

}

}

//查找标签间的内容  可能不止执行一次

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

{

//NSLog(@"标签之间的内容!!!");

[self.str appendString:string];

}

//标签查找结束

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

{

//NSLog(@"标签结束:%@   ,%@",elementName,self.str);

if (![elementName isEqualToString:@"Data"]&&![elementName isEqualToString:@"Movie"]) {

[self.datamodel setValue:self.str forKey:elementName];

}

}

//解析结束

-(void)parserDidEndDocument:(NSXMLParser *)parser

{

NSLog(@"解析结束!!");

NSLog(@"%@",self.models);

}

//解析出错

-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError

{

NSLog(@"解析出错!!!!!!!!%@",parseError);

}

//懒加载

-(NSMutableString*)str

{

if (!_str) {

_str=[NSMutableString new];

}

return _str;

}

-(NSMutableArray*)models

{

if (!_models) {

_models=[NSMutableArray new];

}

return _models;

}

@end