【问题标题】:NSXmlparser does not gets into the did start element method in iphoneNSXmlparser 没有进入 iphone 中的 did start 元素方法
【发布时间】:2011-09-02 07:32:16
【问题描述】:

我有一个基于 xml 的应用程序。我已经编写了所有代码来进行 xml 解析,但主要问题是我的解析器没有进入 didStartElement 方法。它跳过didStartElementfoundCharacters 方法,直接进入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>

【问题讨论】:

  • 请把xml链接发给你
  • 你对我们有什么期望?甚至没有一段代码?
  • +1!从您尝试解析的 XML 中发布一个示例(摘录),以及您设置解析器及其委托的代码 - 包括您的“...didStartElement...”实现 - 直到(并包括)开始解析元素的代码。否则,我们所能做的就是“Kaffeesatzlesen”……哦,对照NSXMLParserheader-file 检查“……didStartElement……”的签名:文档(很少,但是……)有时会有小问题委托方法的选择器中的拼写错误。
  • 嗨@danyowdee,我已经在我的问题中发布了代码并发布了xml文件。我已经编写了上面的代码来解析 xml 文件,但它没有进入 didstartelement 以及如何解析属性值。谢谢
  • 嗨@Aman,我已经在我的问题中添加了xml文件。请检查一下。谢谢

标签: iphone objective-c xml nsxmlparser


【解决方案1】:

检查你编码中的这些想法

[xmlParser setDelegate:self];       
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser setShouldResolveExternalEntities:NO];    
[xmlParser parse];

【讨论】:

  • NSMutableString *returnDataString = [[NSMutableString alloc] initWithData:inData encoding:NSUTF8StringEncoding]; NSLog(@"%@",returnDataString);使用它来查看您的 XML 文件。并检查值是否存在...
  • 我的 xml 文件有点不同,它有属性值。所以如何比较属性值。我知道如何比较元素名但如何比较属性值。请检查我的 xml 文件。谢谢跨度>
  • 是的,我已经在我的代码中使用了它并检查了我的 xml 文件
  • 但我的问题是如何比较属性值
【解决方案2】:

如果您从项目中复制/粘贴了代码,那么为什么没有调用 ...didStartElement:... 的原因是一个小错误:

// 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”。

如果你从文档中复制了选择器,请去提交一个错误——这种类型的东西也让我痛苦了好几次 :-(


更新

为了处理属性,您必须使用传入parser:didStartElement:…attributes: 的字典。 (请参阅“事件驱动的 XML 编程指南” 中的 Handling Elements 以获取更多参考。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-02
    • 2023-04-01
    • 2011-05-22
    • 2016-06-14
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多