X## XML & JSON
XML
SAX 解析
1.创建 XML 解析对象
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"bookstore" withExtension:@"xml"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:fileURL];
2.设置 XML 解析对象
3.开始解析
BOOL flag = [ xmlParser parse ];
if (!flag){
NSL(@"xmlParser parser error!!");
}
NSXMLParser 对象的代理方法:
- (void)parserDidStartDocument:(NSXMLParser *)parser
- (void)parser:(NSXMLParser )parser didStartElement:(NSString )elementName namespaceURI:(NSString )namespaceURI qualifiedName:(NSString )qName attributes:(NSDictionary *)attributeDict
(void)parser:(NSXMLParser )parser foundCharacters:(NSString )string
(void)parser:(NSXMLParser )parser didEndElement:(NSString )elementName namespaceURI:(NSString )namespaceURI qualifiedName:(NSString )qName
当解析 xml标签的文本内容的时候,调用这个方法.在这个方法中,
需要将模型对象保存入数组中或者把标签对应的内容解析出来,保存在模型对象中( KVC)
(void)parserDidEndDocument:(NSXMLParser *)parser
(void)parser:(NSXMLParser )parser parseErrorOccurred:(NSError )parseError
@interface ViewController () <NSXMLParserDelegate>
@property (nonatomic,strong) NSMutableArray *bookStore;
@property (nonatomic,strong) QYBooks *currentBook;
@property (nonatomic,strong) NSString *content;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view,typically from a nib.
}
- (IBAction)saxParse:(UIButton *)sender {
// 1.获取 XML 文件路径
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"bookstore" withExtension:@"xml"];
// 2.创建 XML 文件解析器
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:fileURL];
// 3.设置 XML 的委托
parser.delegate = self;
// 4.开始解析
[parser parse];
}
#pragma mark - xml parser delegate
//解析开始是触发
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
_bookStore = [NSMutableArray array];
}
//遇见元素标签时触发
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// 创建当前的 book 对象
if ([elementName isEqualToString:kBook]) {
_currentBook = [[QYBooks alloc] init];
_currentBook.category = attributeDict[kCategory];
}
if ([elementName isEqualToString:kTitle]) {
_currentBook.lang = attributeDict[kLang];
}
}
//遇见文本内容时触发
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
_content = string;
}
// 遇见元素结束标签是触发
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:kBook]) {
[_bookStore addObject:_currentBook];
}else if ([elementName isEqualToString:@"bookstore"]){
NSLog(@"解析即将完成");
} else
{
[_currentBook setValue:_content forKey:elementName];
}
}
// 解析结束时触发
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"%@",_bookStore);
}
// 解析错误时触发
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSLog(@"%@",parseError);
}