如何通过iPhone中的XML解析在不同的自定义tableview单元格中显示不同的值?

时间:2011-06-30 11:01:30

标签: iphone objective-c xml

我有一个应用程序,其中有一个基于XML的应用程序。这是为了显示当天,明天,后天和后天的天气状况。

我创建了一个自定义表格视图单元格,以便我可以将从XML解析的这些细节显示在这些单元格中。我已经完成了解析器的所有代码并将其显示在控制器上,但问题是在tableview的每个单元格中只显示了一个相同的值。

这是我的元素类代码:

#import <Foundation/Foundation.h>


@interface TWeatherElement : NSObject 
{
    NSString *mIcon;
    //NSString *mForecastdate;
    NSString *mCurrentdate;
    NSString *mConditionname;
    NSString *mMintemp;
    NSString *mMaxtemp;
    NSString *mWind;
    NSString *mHumidity;
    NSString *mWeather;
    NSString *mXmlapireply;

 }

@property (nonatomic,retain) NSString *icon;
//@property (nonatomic,retain) NSString *forecastdate;
@property (nonatomic, retain)NSString *currentdate;
@property (nonatomic,retain)NSString *conditionname;
@property (nonatomic,retain)NSString *mintemp;
@property (nonatomic, retain)NSString *maxtemp;
@property (nonatomic, retain)NSString *wind;
@property (nonatomic, retain)NSString *humidity;
@property (nonatomic, retain)NSString *weather;
@property (nonatomic, retain)NSString *xmlapireply;


@end

和.m

#import "TWeatherElement.h"


@implementation TWeatherElement
@synthesize icon = mIcon;
//@synthesize forecastdate = mForecastdate;
@synthesize currentdate = mCurrentdate;
@synthesize conditionname = mConditionname;
@synthesize mintemp = mMintemp;
@synthesize maxtemp = mMaxtemp;
@synthesize wind = mWind;
@synthesize humidity = mHumidity;
@synthesize weather = mWeather;
@synthesize xmlapireply =mXmlapireply;


-(void)dealloc
{
    [mIcon release];
    //[mForecastdate release];
    [mCurrentdate release];
    [mConditionname release];
    [mMintemp release];
    [mMaxtemp release];
    [mWind release];
    [mHumidity release];
    [mWeather release];
    [mXmlapireply release];
    [super dealloc];
}


@end

这是我的解析器类:

#import "TWeatherElement.h"//this is the class where the elements are Created
#import <Foundation/Foundation.h>


@interface TWeatherParser : NSObject<NSXMLParserDelegate> 
{
    NSString *urlString;

    NSMutableArray *mParserArray;
    //NSXMLParser *mXmlParser;
    NSXMLParser *parser;
    NSMutableString *mCurrentElement;
    BOOL elementFound;
    TWeatherElement *mWeather;

}
@property (nonatomic, retain) NSString *urlString;
//@property (nonatomic, retain) NSMutableArray *tweetArray;
//
@property (nonatomic, retain) NSXMLParser *parser;
@property (nonatomic, retain) NSMutableString *currentElement;
@property (nonatomic, retain)NSMutableArray *mParserArray;
@property (nonatomic, retain) TWeatherElement *weatherobj;

//-(void)getInitialiseWithData:(NSData *)inData;
-(NSMutableArray *)retrieveTweetsFromURL:(NSString *)urlString;
@end





#import "TWeatherParser.h"
#import "JourneyAppDelegate.h"
#import "api.h"
//#define kParsingFinishedNotification @"ParsingFinishedNotification"


@implementation TWeatherParser
@synthesize weatherobj = mWeather;
@synthesize currentElement = mCurrentElement;
@synthesize mParserArray;
@synthesize urlString;
@synthesize parser;


-(id)init
{
    if ((self = [super init]))
    {
        self.mParserArray = [[[NSMutableArray alloc]init]autorelease];
    }
    return self;
}


-(NSMutableArray *)retrieveTweetsFromURL:(NSString *)urlString {

    mParserArray = [[NSMutableArray alloc] init];


    NSURL *urlToRetrieve = [NSURL URLWithString:urlString] ;

    parser = [[NSXMLParser alloc] initWithContentsOfURL:urlToRetrieve];

    [parser setDelegate:self];

    if ([parser parse])
    {
        NSLog(@"Parsed OK");

    } else {
        NSLog(@"There's been a problem :-(");
    }

    return mParserArray;

}



-(void)parser:(NSXMLParser *)parser didStartElement:(NSString*) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict
{

    if ([elementName isEqualToString:@"xml_api_reply"])
    {
        mWeather = [[TWeatherElement alloc]init];
        NSString *data8= [attributeDict objectForKey:@"version"];
        if(data8 !=nil)
            mWeather.xmlapireply =data8 ;
        [mParserArray addObject:mWeather];
    }
    if ([elementName isEqualToString:@"weather"])
    {
        NSString *data0= [attributeDict objectForKey:@"module_id"];
        if(data0 !=nil)
         self.weatherobj.weather=data0 ;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"weather==%@",[attributeDict valueForKey:@"module_id"]);
    }
    if([elementName isEqualToString:@"current_date_time"])
    {
        NSString *data1= [attributeDict objectForKey:@"data"];
        if (data1 !=nil) 
            self.weatherobj.currentdate =data1;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"current_date_time==%@",[attributeDict valueForKey:@"data"]);
    }
    if([elementName isEqualToString:@"condition"])
    {
        NSString *data2= [attributeDict objectForKey:@"data"];
        if (data2 !=nil) 
            self.weatherobj.conditionname=data2;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"condition==%@",[attributeDict valueForKey:@"data"]);

    }
    if([elementName isEqualToString:@"humidity"])
    {
        NSString *data3= [attributeDict objectForKey:@"data"];
        if (data3 !=nil) 
            self.weatherobj.humidity =data3;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"humidity==%@",[attributeDict valueForKey:@"data"]);

    }
    if([elementName isEqualToString:@"icon"])
    {
        NSString *data4= [attributeDict objectForKey:@"data"];
        if (data4 !=nil) 
            self.weatherobj.icon =data4;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"icon==%@",[attributeDict valueForKey:@"data"]);

    }
    if([elementName isEqualToString:@"wind_condition"])
    {
        NSString *data5= [attributeDict objectForKey:@"data"];
        if (data5 !=nil) 
            self.weatherobj.wind =data5;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"wind_condition==%@",[attributeDict valueForKey:@"data"]);
    }
    if([elementName isEqualToString:@"low"])
    {
        NSString *data6= [attributeDict objectForKey:@"data"];
        if (data6 !=nil)                   
            self.weatherobj.mintemp = data6;
        [mParserArray addObject:self.weatherobj];
        NSLog(@"low==%@",[attributeDict valueForKey:@"data"]);
    }
    if([elementName isEqualToString:@"high"])
    {
        NSString *data7= [attributeDict objectForKey:@"data"];
        if (data7 !=nil)                   
            self.weatherobj.maxtemp =data7; 
        [mParserArray addObject:self.weatherobj];
        NSLog(@"high==%@",[attributeDict valueForKey:@"data"]);
    }



}
-(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];
        //[mParserArray release];
    }   
}



-(void)dealloc
{
    [super dealloc];
    self.weatherobj = nil;
    self.currentElement = nil;
}
@end

这是我的控制器类,我在其中设置数组

#import <UIKit/UIKit.h>
#import "TWeatherParser.h"
@class TWeatherParser;


@interface TWeatherController : UITableViewController {

    UITableView *mTableView;
    NSMutableArray *mImage;
    NSMutableArray *weatherarray;
    TWeatherParser *weather;


}
@property (nonatomic, retain) IBOutlet UITableView *mTableView;
@property (nonatomic, retain) NSMutableArray *weatherarray;
@property (nonatomic, retain) TWeatherParser *weather;

@end





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



@implementation TWeatherController
@synthesize mTableView;
@synthesize weatherarray;
@synthesize weather;


#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];

    NSLog(@"About to run the ViewDidLoad superclass method...");
    [super viewDidLoad];

    self.title = @"Everyone";

    self.editButtonItem.possibleTitles = [NSSet setWithObjects:@"Add/Edit", @"Done", nil];

    self.editButtonItem.title = @"Update";

    weatherarray = [[NSMutableArray alloc] init];


    TWeatherParser *xmlController;
    xmlController = [[TWeatherParser alloc] init];

    // Now go and grab the data from the url... 

    weatherarray = [xmlController retrieveTweetsFromURL:kXMLurl];

    NSLog(@"\n\nThere are %d objects in the array...", [weatherarray count]);

    [xmlController release];

}




#pragma mark -
#pragma mark Table view data source

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [weatherarray count];

}


// 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 = [weatherarray 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];
    }
//Here it is creating some problem here same value is getting displayed for every cells.
    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;
}



- (void)dealloc {
    [super dealloc];
    [weatherarray release];
    [weather release];
    [mTableView release];
}


@end

3 个答案:

答案 0 :(得分:0)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
   static NSString *CellIdentifier = @"Cell";

  ListDetailCell *cell= [[[ListDetailCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

tableView.backgroundColor = [UIColor whiteColor];

 if (cell == nil) 
 {
  cell = [[[ListDetailCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier]
        autorelease];
  }

 switch (indexPath.row)
{
case 0:
    NSLog(@"%d",indexPath.row);
    cell.leadingLabel.text = @"Name: ";
    cell.leadingLabel.font = [UIFont fontWithName:LABELS_FONT_NAME_BOLD size:11.0f];
    cell.leadingLabel.textColor = FONT_GREEN_COLOR;

    cell.volInfo.text = volRow.volName;
    cell.volInfo.font = [UIFont fontWithName:LABELS_FONT_NAME size:11.0f];
    break;
case 1:
    NSLog(@"%d",indexPath.row);
    cell.leadingLabel.text = @"Address: ";
    cell.leadingLabel.font = [UIFont fontWithName:LABELS_FONT_NAME_BOLD size:11.0f];
    cell.leadingLabel.textColor = FONT_GREEN_COLOR;

    cell.volInfo.text = volRow.volAddress;
    cell.volInfo.font = [UIFont fontWithName:LABELS_FONT_NAME size:11.0f];
    break;
case 2:
    NSLog(@"%d",indexPath.row);
    cell.leadingLabel.text = @"Phone: ";
    cell.leadingLabel.font = [UIFont fontWithName:LABELS_FONT_NAME_BOLD size:11.0f];
    cell.leadingLabel.textColor = FONT_GREEN_COLOR;

    cell.volInfo.text = volRow.phone;
    cell.volInfo.font = [UIFont fontWithName:LABELS_FONT_NAME size:11.0f];
    break;
case 3:
    NSLog(@"%d",indexPath.row);
    cell.leadingLabel.text = @"Email: ";
    cell.leadingLabel.font = [UIFont fontWithName:LABELS_FONT_NAME_BOLD size:11.0f];
    cell.leadingLabel.textColor = FONT_GREEN_COLOR;

    cell.volInfo.text = volRow.email;
    cell.volInfo.font = [UIFont fontWithName:LABELS_FONT_NAME size:11.0f];
    break;

default:
    NSLog(@"Out of Range ",indexPath.row);
    break;
}

return cell;
}

如果要在不同的单元格中显示不同的值,则必须使用switch case来检测行索引:

volRow变量保存您要显示的解析数据......

答案 1 :(得分:0)

Apple的SeismicXML确实非常适合并且很容易适应。

http://developer.apple.com/library/ios/#samplecode/SeismicXML/

答案 2 :(得分:0)

试试这个

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
        //tableViewDataSource should contain your data returned from parsing
        //Here put a NSLog to print the Array Count just know you are getting right values 
    return [tableViewDataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
     UICustomTableViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; //Create cell
    if(cell == nil)
    {
        cell = [[[UICustomTableViewCell alloc] init] autorelease];
        // Initialize All controls here if you want to
        //This If statement will execute (Number of visible Cells) number of times
    }
    else
    {
        // when Reused get the controls here
    }
    // Assign the data here
    cell.customlabel.text =[tableDataSourceArray objectAtIndex:indexPath.row];

    return cell;
}

如果您遇到问题,请告诉我。