iPhone开发【十九】XML解析之NSXMLParser(使用Web Services查询火车信息)
连接输出口in putTrainInfo及操作queryByTrainId,如下:
发布日期:2021-09-28 18:46:33
浏览次数:14
分类:技术文章
本文共 6378 字,大约阅读时间需要 21 分钟。
转载请注明出处,原文网址: 作者:张燕广
实现的功能: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
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、运行效果如下:
需要源码的网友请留言哦
转载地址:https://blog.csdn.net/h3c4lenovo/article/details/8568207 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月18日 23时00分19秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
水平切分与垂直切分
2021-06-30
MySQL引擎
2021-06-30
MySQL下的NoSQL解决方案HandlerSocket
2021-06-30
Apache服务器下使用 ab 命令进行压力测试
2021-06-30
查看Firefox中的缓存
2021-06-30
http header头设置反向代理不缓存
2021-06-30
配置MySQL主从复制
2021-06-30
CI框架如何删除地址栏的 index.php
2021-06-30
expires与etag控制页面缓存的优先级
2021-06-30
取消掉Transfer-Encoding:chunked
2021-06-30
HTTP协议中的Tranfer-Encoding:chunked编码解析
2021-06-30
JavaScript面向对象编程
2021-06-30
在Javascript中使用面向对象的编程
2021-06-30
由浅入深剖析.htaccess
2021-06-30
php函数serialize()与unserialize()
2021-06-30
PHP Webservice的发布与调用
2021-06-30
php反射类 ReflectionClass
2021-06-30
php扩展xdebug基本使用
2021-06-30
为 PHP 应用提速、提速、再提速
2021-06-30
Linux下gedit显示行号
2021-06-30