NSXmlparser没有进入iphone中的did start element方法

如何解决NSXmlparser没有进入iphone中的did start element方法

| 我有一个基于XML的应用程序。我已经编写了所有代码来进行xml解析,但是主要的问题是我的解析器没有进入
didStartElement
方法。它跳过
didStartElement
foundCharacters
方法,直接进入
didEndElement
,并在我的数组中返回计数0。可能是什么问题?我已经与xml的适当元素进行了比较。 这是我的api方法;通过这种方法,我得到xml文件。
    #import <Foundation/Foundation.h>

    @interface api : NSObject {
        NSError *error;
        NSURLResponse *response;
        NSData *dataReply;


    }
    @property (nonatomic,retain)NSData *dataReply;

    -(NSData *)getBusXMLAtStop:(NSString*)stopnumber;
    @end


    #import \"api.h\"


    @implementation api
    @synthesize dataReply;
    //@synthesize stringReply;

    -(NSData *)getBusXMLAtStop:(NSString*)stopnumber
    {


        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: 
                                        [NSURL URLWithString: [NSString stringWithFormat:@\"http://www.google.com/ig/api?weather=,50500000,30500000\",stopnumber]]];
        [request setHTTPMethod: @\"GET\"];
        dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            NSLog(@\"%@\",dataReply);
        return dataReply;
    }

    -(void)dealloc
    {
        [super dealloc];
        [dataReply release];
    }

    @end
这是我的解析器类,在其中解析xml的每个元素:
    #import \"TWeatherElement.h\"//this is the class where the elements are Created
    #import <Foundation/Foundation.h>


    @interface TWeatherParser : NSObject<NSXMLParserDelegate> 
    {
        NSMutableArray *mParserArray;//this is the array i  have in the parser class to hold the elements
        NSXMLParser *mXmlParser;
        NSMutableString *mCurrentElement;
        BOOL elementFound;
        TWeatherElement *mWeatherobj;

    }
    @property (nonatomic,retain) NSMutableString *currentElement;
    @property (nonatomic,retain)NSMutableArray *mParserArray;
    @property (nonatomic,retain) TWeatherElement *weatherobj;

    -(void)getInitialiseWithData:(NSData *)inData;

    @end



    #import \"TWeatherParser.h\"
    #import \"JourneyAppDelegate.h\"
    #import \"api.h\"

    @implementation TWeatherParser
    @synthesize weatherobj = mWeatherobj;
    @synthesize currentElement = mCurrentElement;
    @synthesize mParserArray;


    -(void)getInitialiseWithData:(NSData *)inData
    {
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:inData];

        [parser setDelegate:self];
        [parser setShouldProcessNamespaces:NO];
        [parser setShouldReportNamespacePrefixes:NO];
        [parser setShouldResolveExternalEntities:NO];

        [parser parse];

      [parser release];
    }



    -(void)parser:(NSXMLParser *)parser didStartElement:(NSString*) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString*)qualifiedName attribute:(NSDictionary*)attributeDict
    {
        if (nil!= qualifiedName)
        {
            elementName = qualifiedName;
        }
        if ([elementName isEqualToString:@\"weather\"])

        {
            [mParserArray addObject:elementName];
            self.weatherobj = [[TWeatherElement alloc]init];
        }
        else if([elementName isEqualToString:@\"current_date_time\"]||
                [elementName isEqualToString:@\"condition\"]||
                [elementName isEqualToString:@\"humidity\"]||
                [elementName isEqualToString:@\"icon d\"]||
                [elementName isEqualToString:@\"wind_condition\"]||
                [elementName isEqualToString:@\"low\"]||
                [elementName isEqualToString:@\"high\"])
        {
            self.currentElement = [NSMutableString string];
        }
        else 
        {
            self.currentElement = nil;
        }


    }


    -(void)parser:(NSXMLParser*)parser foundCharacters:(NSString*)string
    {
        if (nil!= self.currentElement)
        {
            [self.currentElement appendString:string];
        }
    }

    -(void)parser:(NSXMLParser *)parser didEndElement:(NSString*)elementName namespaceURI:(NSString*)namespaceURI qualifiedName:(NSString*)qName
    {
        if (nil != qName)
        {
            elementName  = qName;
        }
        if ([elementName isEqualToString:@\"current_date_time\"]) 
        {
            self.weatherobj.currentdate = self.currentElement;

        }
    else if ([elementName isEqualToString:@\"condition\"]) 
    {
        self.weatherobj.conditionname = self.currentElement;

    }
    else if ([elementName isEqualToString:@\"humidity\"]) 
    {
        self.weatherobj.humidity = self.currentElement;

    }
    else if ([elementName isEqualToString:@\"icon\"]) 
    {
        self.weatherobj.icon = self.currentElement;

    }
    else if ([elementName isEqualToString:@\"wind_condition\"]) 
    {
        self.weatherobj.wind = self.currentElement;

    }
    else if ([elementName isEqualToString:@\"low\"]) 
    {
        self.weatherobj.mintemp = self.currentElement;

    }
    else if ([elementName isEqualToString:@\"high\"]) 
    {
        self.weatherobj.maxtemp = self.currentElement;

    }

    else if ([elementName isEqualToString:@\"weather\"]) 
    {
        [mParserArray addObject:self.weatherobj];
        NSLog(@\"mDataArray count = %d\",[mParserArray count]);
        [self.weatherobj release];


    }   
    }


    -(void)dealloc
    {
        self.weatherobj = nil;
        self.currentElement = nil;
        [super dealloc];
    }
    @end
这是tableviewcontroller类,我要在其中显示从tableviewcell上的xml获取的值
    #import <UIKit/UIKit.h>
    #import \"TWeatherParser.h\"
    @class TWeatherParser;


    @interface TWeatherController : UITableViewController {

        UITableView *mTableView;
        NSMutableArray *mImage;
        NSMutableArray *weatherarray;//this is the array that has been created in this class.
        TWeatherParser *weather;




    }
    @property (nonatomic,retain) IBOutlet UITableView *mTableView;


    @end




    //
    //  TWeatherController.m
    //  Journey
    //
    //  Created by raji.nair on 5/3/11.
    //  Copyright 2011 __MyCompanyName__. All rights reserved.
    //

    #import \"TWeatherController.h\"
    #import \"TWeatherCell.h\"
    #import \"TWeatherElement.h\"
    #import \"TWeatherParser.h\"
    #import \"api.h\"


    @implementation TWeatherController
    @synthesize mTableView;


    #pragma mark -
    #pragma mark Initialization

    - (id)initWithStyle:(UITableViewStyle)style {
        // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
        style = UITableViewStyleGrouped;
        if (self = [super initWithStyle:style]) {
        }
        return self;
    }



    #pragma mark -
    #pragma mark View lifecycle

    /*
    - (void)viewDidLoad {
        [super viewDidLoad];

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }
    */


    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
        api *ap = [[api alloc]init];
        NSData *aData = [ap getBusXMLAtStop:@\"1\"];
        NSString *str = [[NSString alloc] initWithData:aData encoding:NSUTF8StringEncoding];

        //NSInteger value = [str intValue];
        if (str!= NULL)
        {
            NSLog(@\"this is success %@\",ap.dataReply);
            TWeatherParser *parser = [[TWeatherParser alloc]init];
            [parser getInitialiseWithData:ap.dataReply];
            [parser release];


        }
        else 
        {
            UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@\"Alert\" message:@\"cannot fetch\" delegate:self cancelButtonTitle:@\"OK\" otherButtonTitles:nil];
            [alertview show];
            [alertview release];
        }


        [ap release];



    }



    #pragma mark -
    #pragma mark Table view data source

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        // Return the number of sections.
        return 2;
    }


    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        // Return the number of rows in the section.

        **return [weather.mParserArray count];**.//Here i am having a doubt that which array should i count over here


    }


    // Customize the appearance of table view cells.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *CellIdentifier = @\"Cell\";


       TWeatherCell *cell =(TWeatherCell *) [mTableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[TWeatherCell alloc] initWithStyle:UITableViewStyleGrouped reuseIdentifier:CellIdentifier] autorelease];
        }
        TWeatherElement *newobj = [weather.mParserArray objectAtIndex:indexPath.row];
        if ([newobj.icon isEqualToString:@\"http://\\n\"])
        {
            cell.weatherimage.image = [UIImage imageNamed:@\"listIcon-H.png\"];
        }
        else {
            NSData *imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:newobj.icon]];
            cell.weatherimage.image = [UIImage imageWithData:imageData];
            [imageData release];
        }
        cell.reportdate.text = newobj.currentdate;
        cell.conditionname.text = newobj.conditionname;
        cell.twotemp.text = [NSString stringWithFormat:@\"Temp:%@/%@\",newobj.mintemp,newobj.maxtemp];
        cell.twodirection.text = newobj.wind;
        cell.humidity.text = newobj.humidity;

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        // Configure the cell...

        return cell;
    }


    #pragma mark -
    #pragma mark Table view delegate

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        // Navigation logic may go here. Create and push another view controller.
        /*
        <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@\"<#Nib name#>\" bundle:nil];
         // ...
         // Pass the selected object to the new view controller.
        [self.navigationController pushViewController:detailViewController animated:YES];
        [detailViewController release];
        */
    }

    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *) indexPath
    {
        return 100.0;


    }


    #pragma mark -
    #pragma mark Memory management

    - (void)didReceiveMemoryWarning {
        // Releases the view if it doesn\'t have a superview.
        [super didReceiveMemoryWarning];

        // Relinquish ownership any cached data,images,etc. that aren\'t in use.
    }

    - (void)viewDidUnload {
        // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
        // For example: self.myOutlet = nil;
    }


    - (void)dealloc {
        [super dealloc];
    }


    @end
XML文件;
<?xml version=\"1.0\"?><xml_api_reply version=\"1\"><weather module_id=\"0\" tab_id=\"0\" mobile_row=\"0\" mobile_zipped=\"1\" row=\"0\" section=\"0\" ><forecast_information><city data=\"\"/><postal_code data=\"\"/><latitude_e6 data=\"50500000\"/><longitude_e6 data=\"30500000\"/><forecast_date data=\"2011-05-26\"/><current_date_time data=\"2011-05-26 04:00:00 +0000\"/><unit_system data=\"US\"/></forecast_information><current_conditions><condition data=\"Clear\"/><temp_f data=\"52\"/><temp_c data=\"11\"/><humidity data=\"Humidity: 62%\"/><icon data=\"/ig/images/weather/sunny.gif\"/><wind_condition data=\"Wind: NW at 9 mph\"/></current_conditions><forecast_conditions><day_of_week data=\"Thu\"/><low data=\"48\"/><high data=\"68\"/><icon data=\"/ig/images/weather/mostly_sunny.gif\"/><condition data=\"Mostly Sunny\"/></forecast_conditions><forecast_conditions><day_of_week data=\"Fri\"/><low data=\"52\"/><high data=\"75\"/><icon data=\"/ig/images/weather/mostly_sunny.gif\"/><condition data=\"Mostly Sunny\"/></forecast_conditions><forecast_conditions><day_of_week data=\"Sat\"/><low data=\"55\"/><high data=\"81\"/><icon data=\"/ig/images/weather/mostly_sunny.gif\"/><condition data=\"Mostly Sunny\"/></forecast_conditions><forecast_conditions><day_of_week data=\"Sun\"/><low data=\"55\"/><high data=\"86\"/><icon data=\"/ig/images/weather/mostly_sunny.gif\"/><condition data=\"Partly Sunny\"/></forecast_conditions></weather></xml_api_reply>
    

解决方法

在您的编码中检查这些想法
[xmlParser setDelegate:self];       
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser setShouldResolveExternalEntities:NO];    
[xmlParser parse];
    ,如果您已从项目中复制/粘贴了代码,则未打出minor9ѭ的原因是一个较小的错字:
// Your method:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString*) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString*)qualifiedName attribute:(NSDictionary*)attributeDict
// NSXMLParserDelegate\'s method:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
阅读:您在选择器的最后一部分缺少一个\“ s \”。 如果您已经从文档中复制了选择器,请去提交一个错误-这种类型的东西也咬了我很多次:-( 更新资料 为了处理属性,您必须使用在ѭ11中传递的字典。 (有关更多参考,请参见《事件驱动的XML编程指南》中的处理元素。)     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-