iPhone開發【十九】XML解析之NSXMLParser(使用Web Services查詢火車信息)

轉載請註明出處,原文網址:http://blog.csdn.net/m_changgong/article/details/8246333 作者:張燕廣

實現的功能: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、運行效果如下:

需要源碼的網友請留言哦

發佈了183 篇原創文章 · 獲贊 9 · 訪問量 103萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章