您的位置:首页 > 其它

iPhone开发【十九】XML解析之NSXMLParser(使用Web Services查询火车信息)

2012-12-01 14:42 531 查看
[b][b][b][b][b][b][b][b][b][b][b][b][b]转载请注明出处,原文网址:/article/1354663.html
作者:张燕广
[/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b][/b]

实现的功能:1)根据火车车次查询火车信息;2)演示XML解析类NSXMLParser的应用。

关键词:NSXMLParser XML解析

1、新建一个Sigle View Application,命名为Train,工程结构如下:



2、修改ViewController.xib,添加一个TextField控件和一个Button。

3、修改ViewController.h,如下:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSXMLParserDelegate, NSURLConnectionDelegate> {
    bool elementFound;
    uint count;
}

@property(strong,nonatomic)NSURLConnection *conn;
@property(strong,nonatomic)NSString *soapMessage;
@property(strong,nonatomic)NSXMLParser *xmlParser;
@property(strong,nonatomic)NSMutableData *responseData;
@property(strong,nonatomic)NSMutableString *queryResult;
@property(strong,nonatomic)NSString *trainId;
@property(strong,nonatomic)NSString *destElement;

@property(strong,nonatomic)IBOutlet UITextField *inputTrainInfo;
-(IBAction)queryByTarinID:(id)sender;
@end
连接输出口inputTrainInfo及操作queryByTrainId,如下:



4、修改ViewController.m,如下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize conn;
@synthesize soapMessage;
@synthesize xmlParser;
@synthesize responseData;
@synthesize trainId;
@synthesize destElement;
@synthesize queryResult;
@synthesize inputTrainInfo;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    //解析出的第几个值
    count = 0;
}

-(IBAction)queryByTarinID:(id)sender{
    count = 0;
    trainId = inputTrainInfo.text;
    destElement = @"getStationAndTimeByTrainCodeResult";
    soapMessage = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
        "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
        "<soap12:Body>"
        "<getStationAndTimeByTrainCode xmlns=\"http://WebXml.com.cn/\">"
        "<TrainCode>%@</TrainCode>"
        "<UserID>%@</UserID>"
        "</getStationAndTimeByTrainCode>"
        "</soap12:Body>"
        "</soap12:Envelope>",trainId,@""];    
    NSLog(@"%@",soapMessage);
    // 创建URL
    NSURL *url = [NSURL URLWithString:@"http://webservice.webxml.com.cn/WebServices/TrainTimeWebService.asmx"];
    // 根据上面的URL创建一个请求
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
    // 添加请求的详细信息,与请求报文前半部分的各字段对应
    [req addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    // 设置请求行方法为POST,与请求报文第一行对应
    [req setHTTPMethod:@"POST"];
    // 将SOAP消息加到请求中
    [req setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    
    // 创建连接
    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if (conn) {
        responseData = [NSMutableData data];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

-(void)showQueryResult{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"查询结果"
                                                    message:[NSString stringWithFormat:@"%@", queryResult]
                                                   delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark -
#pragma mark URL Connection Data Delegate Methods

// 刚开始接受响应时
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response{
    [responseData setLength: 0];
}

// 每接收到一部分数据就追加到responseData中
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data {
    [responseData appendData:data];
}

// 出现错误时
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error {
    conn = nil;
    responseData = nil;
}

// 完成接收数据时调用
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSString *responseXML = [[NSString alloc] initWithBytes:[responseData mutableBytes]
                                                length:[responseData length]
                                              encoding:NSUTF8StringEncoding];
    printf("\n\n");
    
    // 打印出得到的XML
    NSLog(@"\n%@", responseXML);
    // 使用NSXMLParser解析出想要的结果
    xmlParser = [[NSXMLParser alloc] initWithData: responseData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities: YES];
    [xmlParser parse];
}

// 开始解析一个元素名
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict {
    if ([elementName isEqualToString:destElement]) {
        if (!queryResult) {
            queryResult = [[NSMutableString alloc] init];
        }
        elementFound = YES;
    }
    
}

// 追加找到的元素值,一个元素值可能会追加多次
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string {
    if (elementFound) {
        switch (count++) {
            case 0:
                //NSLog(@"车次%@",string);
                [queryResult appendString: [NSString stringWithFormat:@"车次:%@\n",string]];
                break;
            case 1:
                //NSLog(@"发站%@",string);
                if([string isEqualToString:@"数据没有被发现"]){
                    [queryResult deleteCharactersInRange:NSMakeRange(0, [queryResult length])];
                    [queryResult appendString: [NSString stringWithFormat:@"%@",string]];
                    //停止解析
                    [xmlParser abortParsing];
                    [self showQueryResult];
                    return;
                }
                [queryResult appendString: [NSString stringWithFormat:@"发站:%@\n",string]];
                break;
            case 2:
                //NSLog(@"到站%@",string);
                [queryResult appendString: [NSString stringWithFormat:@"到站:%@\n",string]];
                break;
            case 3:
                break;
            case 4:
                //NSLog(@"发车时间%@",string);
                [queryResult appendString: [NSString stringWithFormat:@"发车时间:%@\n",string]];
                break;
            case 5:
                break;
            case 6:
                //NSLog(@"到站时间%@",string);
                [queryResult appendString: [NSString stringWithFormat:@"到站时间:%@\n",string]];
                break;
            case 7:
                //NSLog(@"里程%@",string);
                [queryResult appendString: [NSString stringWithFormat:@"里程:%@公里\n",string]];
                break;
            case 8:
                //NSLog(@"运行时间%@",string);
                [queryResult appendString: [NSString stringWithFormat:@"运行时间:%@小时\n",string]];
                break;
            default:
                break;
        }
        
    }
    //[queryResult appendString: string];
}

// 结束解析这个元素名
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([elementName isEqualToString:destElement]) {
        [self showQueryResult];
        elementFound = FALSE;
        //停止解析
        [xmlParser abortParsing];
    }
}

// 解析整个文件结束
- (void)parserDidEndDocument:(NSXMLParser *)parser {
    if (responseData) {
        responseData = nil;
    }
}

// 出错,例如强制停止解析
- (void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    if (queryResult) {
        queryResult = nil;
    }
}
@end


5、运行效果如下:





需要源码的网友请留言哦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: