iPhone/iPad 开发: 解析本地/网络上的xml文件

1、解析本地xml文件

Java代码   收藏代码
//找到本地test.xml文件  

NSString*path = [[NSBundlemainBundle]   pathForResource:@"test" ofType:@ "xml" ];   NSFileHandle*file = [NSFileHandlefileHandleForReadingAtPath:path];  
NSData*data = [file readDataToEndOfFile];
//得到xml文件  
//开始解析  
NSXMLParser* xmlRead = [[NSXMLParseralloc] initWithData:data];
//初始化NSXMLParser对象  
[data release]; 
[xmlRead setDelegate:self];//设置NSXMLParser对象的解析方法代理  
[xmlRead parse];//调用代理解析NSXMLParser对象,看解析是否成功   
//找到本地test.xml文件
 NSString*path = [[NSBundlemainBundle]   pathForResource:@"test"ofType:@"xml"];
 NSFileHandle*file = [NSFileHandlefileHandleForReadingAtPath:path];
 NSData*data = [file readDataToEndOfFile];//得到xml文件

//开始解析
NSXMLParser* xmlRead = [[NSXMLParseralloc] initWithData:data];//初始化NSXMLParser对象
[data release];
[xmlRead setDelegate:self];//设置NSXMLParser对象的解析方法代理
[xmlRead parse];//调用代理解析NSXMLParser对象,看解析是否成功



2、解析网络xml文件

Java代码   收藏代码
#define URIString @ "http://192.168.247.76:8899/hisyo_cn/test.xml"  
//首先链接网络文件  
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:URIString]  cachePolicy:NSURLRequestUseProtocolCachePolicy  timeoutInterval:15 ];     NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];     if  (theConnection) { 
               //得到文件数据   
       receivedData=[[NSMutableData data] retain];  
    }   
    else   
    {  
       NSLog(@"error" ); 
    }  

- (void )connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {       [receivedData setLength:0 ]; 
}  
 
- (void )connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {       [receivedData appendData:data];        

- (void )connection:(NSURLConnection *)connection  didFailWithError:(NSError *)error  { 
   [connection release];  
    [receivedData release];  
    NSLog(@"Error" );  
   //超过设定好的链接时间显示链接失败   
    [theContent setText:@"Connection defeat" ]; 

- (void )connectionDidFinishLoading:(NSURLConnection *)connection  {       NSString *content = [[NSString alloc] initWithData: receivedData encoding: NSUTF8StringEncoding];   NSLog(@"content: %@" ,content);  
[theContent setText:content];  
 //开始解析获取的receivedData   
xmlRead = [[NSXMLParser alloc] initWithData:receivedData]; 
[xmlRead setDelegate:self];//设置NSXMLParser对象的解析方法代理  
[xmlRead parse];//调用代理解析NSXMLParser对象,看解析是否成   //NSString *content = [[NSString alloc] initWithData: receivedData encoding: NSJapaneseEUCStringEncoding];   

[connection release];  
[receivedData release];

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值