【iOS开发】原生XML解析

前端之家收集整理的这篇文章主要介绍了【iOS开发】原生XML解析前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

初始化方法

Initializes a parser with the XML content referenced by the given URL.

- initWithData: Designated Initializer

Initializes a parser with the XML contents encapsulated in a given data object.






Initializes a parser with the XML contents from the specified stream and parses it..


一个简单的xml文件解析


实例:

.h

#import<Foundation/Foundation.h>

@interfaceMyXMLParser :NSObject<NSXMLParserDelegate>

@property(nonatomic,strong)NSMutableArray* arrM;

-(void)test;

@end


.m

#import"MyXMLParser.h"

#import"Student.h"

MyXMLParser()

{

NSMutableString* _elementStr;

Student* student;

}

@end

@implementationMyXMLParser

-(void)test

{

NSString* path = [[NSBundlemainBundle]pathForResource:@"test"ofType@"xml"];

NSXMLParser* parser = [[alloc]initWithContentsOfURL:[NSURLURLWithString:path]];

parser.delegate=self;

[parserparse];

}

#pragma mark - 解析开始

-(void)parserDidStartDocument:(NSXMLParser*)parser

{

_arrM= [NSMutableArrayarray];

_elementStr= [NSMutableStringstring];

}

#pragma mark -解析完成

-(void)parserDidEndDocument:(NSXMLParser*)parser

{

NSLog(@"%@",_arrM);

}

#pragma mark -

-(void)parser:(NSXMLParser*)parser didStartElement:(nonnullNSString*)elementName namespaceURI:(nullableNSString*)namespaceURI qualifiedName:(NSString*)qName attributes:(NSDictionary<NSString*,NSString*> *)attributeDict

{

if([elementNameisEqualToString:@"student"]) {

student= [[Studentalloc]init];

}

[_elementStrsetString@"" #pragma mark 循环查找节点内容

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

{

// 拼接字符串

[_elementStrappendString:string];

}


#pragma mark 一个节点完成

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

{

NSString*result = [NSStringstringWithString:_elementStr];

@"student"]) {

[_arrMaddObject:student];

}else@"name"]){

student.name= result;

}@"sex"]) {

sex= result;

}

}

#pragma mark - 出错

-(NSXMLParser*)parser validationErrorOccurred:(NSError*)validationError

{

[removeAllObjects];

NSLog(@"%@"错误 ");

description);

}

其他的代理方法不一一详述

猜你在找的XML相关文章