iOS:处理XML文件

 

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);

}

 

你可能感兴趣的:(xml)