码迷,mamicode.com
首页 > 移动开发 > 详细

iOS:处理XML文件

时间:2014-10-09 22:09:47      阅读:407      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   strong   文件   

 

NSXMLParser是标准库类

Book.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--Document created by: lishujun, code-style with XmlGrid Online XML Editor, http://xmlgrid.net -->
<book>
    <!--
    <summary>
        <author>金庸</author>
        <content>sfdgasidfhasdfb</content>
    </summary>
     -->

<chapters>
    <chapter name="hello">hello,world</chapter>
    <chapter name="lishujun">
        i‘m lishujun
        sdfsdfs        aaaasdfsdf
        qqqqqqqq
    </chapter>
    <chapter name="lishujun2">i‘m lishujun2</chapter>
</chapters>
</book>

 

XmlElement.h
#import <Foundation/Foundation.h>

@interface XmlElement : NSObject
@property (strong, nonatomic) NSString *elementName;
@property (strong, nonatomic) NSString *text;
@property (strong, nonatomic) NSDictionary *attributeDict;
@end
XmlElement.m
#import "XmlElement.h"

@implementation XmlElement
@synthesize elementName;
@synthesize text;
@synthesize attributeDict;
@end

 

BookXmlParser.h

#import <Foundation/Foundation.h>
#import "XmlElement.h"

@interface BookXMLParser : NSObject <NSXMLParserDelegate>
{
    XmlElement *_element;
    NSXMLParser *_parser;
}


-(id)initWithData:(NSData*)data;
-(BOOL)parse;

@end

BookXmlParser.m

#import "BookXMLParser.h"
#import "XmlElement.h"

@implementation BookXMLParser

-(id)initWithData:(NSData*)data
{
    if (self) {
        _parser = [[NSXMLParser alloc]initWithData:data];
        _parser.delegate = self;
    }
    return self;
}

-(BOOL)parse
{
    _element = nil;
    return [_parser parse];
}

-(void)  parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
   namespaceURI:(NSString *)namespaceURI
  qualifiedName:(NSString *)qName
     attributes:(NSDictionary *)attributeDict
{
    
    [self processElement];
    
    _element = [[XmlElement alloc]init];
    _element.elementName = elementName;
    _element.attributeDict = attributeDict;
    _element.text = @"";
}

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([_element.text isEqualToString:@""]) {
        _element.text = string;
        //NSLog(@"Now element is %@", _element.text);
    }
}

-(void) processElement
{
    if (_element == nil) {
        return;
    }
    
    NSLog(@"process:");
    NSLog(@"%@, %@", _element.elementName, _element.text);
}

 

iOS:处理XML文件

标签:style   blog   http   color   io   os   ar   strong   文件   

原文地址:http://www.cnblogs.com/code-style/p/4014240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!