首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

IOS学习札记(18)解析xml

2013-02-02 
IOS学习笔记(18)解析xml通过NSXMLParser来解析XML创建一个名为MyXML.xml文件?xml version 1.0 encodi

IOS学习笔记(18)解析xml

通过NSXMLParser来解析XML

创建一个名为MyXML.xml文件

<?xml version = "1.0" encoding = "UTF-8" ?>

<root>

    <person id = "1">

        <firstName>Anthony</firstName>

        <lastName>Robbins</lastName>

        <age>51</age>

    </person>

    <person id = "2">

        <firstName>Richard</firstName>

        <lastName>Branson</lastName>

        <age>61</age>

    </person>

</root>

定义一个NSXMLParser类型的属性

#import <UIKit/UIKit.h>


@class ViewController;


@interface AppDelegate :UIResponder <UIApplicationDelegate,NSXMLParserDelegate>


@property (strong,nonatomic) UIWindow *window;


@property (strong,nonatomic) ViewController *viewController;


@property (strong,nonatomic) NSXMLParser *xmlParser;


@end

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    NSString *xmlFilePath = [[NSBundlemainBundle]pathForResource:@"MyXML"ofType:@"xml"];

   NSData *xml = [[NSDataalloc]initWithContentsOfFile:xmlFilePath];

   xmlParser = [[NSXMLParseralloc]initWithData:xml];

   xmlParser.delegate =self;

   if([xmlParserparse]){

        NSLog(@"The XML is parsed");

    }else{

        NSLog(@"Failed to parse the XML");

    }

    self.window = [[[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]]autorelease];

    // Override point for customization after application launch.

    self.viewController = [[[ViewControlleralloc] initWithNibName:@"ViewController"bundle:nil]autorelease];

    //self.window.rootViewController = self.viewController;

    UINavigationController *nav = [[UINavigationControlleralloc]initWithRootViewController:self.viewController];

    [self.windowaddSubview:nav.view];

    [self.windowmakeKeyAndVisible];

    return YES;

}

首先把文件内容读取到一个NSData实例对象中,然后使用initWithData:来初始化我们的XML parser,并把我们从xml文件中读取出来的数据传进去。之后我们可以调用XML parser的parser方法来开始解析处理。这个方法会zus当前线程,直至解析处理结束。

parserDidStartDocument:解析开始的时候调用该方法。

parserDidEndDocument:解析结束的时候调用该方法。

parser:didStartElement:namespaceURI:qualifiedName:attributes:在XML document中,当解析器在解析的时候遇到了一个新的element时会被调用该方法。

parser:didEndElement:namespaceURI:qualifiedName:当前节点结束之后会调用。

parser:foundCharacters:当解析器在解析文档内容的时候被调用。


热点排行