IOS学习笔记(18)解析xml

本文介绍如何利用NSXMLParser来解析XML文件。通过创建一个包含个人信息的XML文件,演示了如何读取文件内容到NSData对象,初始化NSXMLParser并进行解析。同时详细解释了XML解析过程中的关键回调方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过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 = [[NSBundle mainBundle]pathForResource:@"MyXML" ofType:@"xml"];

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

xmlParser = [[NSXMLParser alloc]initWithData:xml];

xmlParser.delegate = self;

if([xmlParser parse]){

NSLog(@"The XML is parsed");

}else{

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

}

self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

// Override point for customization after application launch.

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

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

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

[self.window addSubview:nav.view];

[self.window makeKeyAndVisible];

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:当解析器在解析文档内容的时候被调用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值