xml parsing is done but the values are not added to the array in iphone
<?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_informatioin have the n>
- <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>
</weather>
</xml_api_reply>
Hi this is element .h-------------------/
#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
this is element .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
this is parser.h---------------/
#import "TWeatherElement.h"//this is the class where the elements are Created
#import <Foundation/Foundation.h>
@interface TWeatherParser : NSObject<NSXMLParserDelegate>
{
NSMutableArray *mParserArray;
NSXMLParser *mXmlParser;
NSMutableString *mCurrentElement;
BOOL elementFound;
TWeatherElement *mWeather;
}
@property (nonatomic, retain) NSMutableString *currentElement;
@property (nonatomic, retain)NSMutableArray *mParserArray;
@property (nonatomic, retain) TWeatherElement *weatherobj;
-(void)getInitialiseWithData:(NSData *)inData;
@end
this is parser.m--------------------/
#import "TWeatherParser.h"
#import "JourneyAppDelegate.h"
#import "api.h"
#import "TWeatherController.h"
//#define kParsingFinishedNotification @"ParsingFinishedNotification"
@implementation TWeatherParser
@synthesize weatherobj = mWeather;
@synthesize currentElement = mCurrentElement;
@synthesize mParserArray;
-(id)init
{
if (self = [super init])
{
self.currentElement =[[NSMutableString alloc]init];
mWeather =nil;
}
return self;
}
-(void)getInitialiseWithData:(NSData *)inData
{
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:inData];
[parser setDelegate:self];
[parser setShouldProcessNamespaces:YES]; //YES if the receiver should report the namespace and qualified name of each element, NO otherwise. The default value is NO
[parser setShouldReportNamespacePrefixes:YES]; //YES if the receiver should report the scope of namespace declarations, NO otherwise. The default value is NO.
[parser setShouldResolveExternalEntities:NO];//YES if the receiver should report declarations of external entities, NO otherwise. The default value is NO
[parser parse];
NSLog(@"%@",parser);
[parser release];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString*) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString*)qualifiedName attributes:(NSDictionary*)attributeDict
{
//
// if (nil!= qualifiedName)
// {
// elementName = qualifiedName;
// }
// if ([elementName isEqualToString:@"weather"])
// {
// self.weatherobj = [[TWeatherElement alloc]init];
// }
// else if([elementName isEqualToString:@"cu开发者_StackOverflow中文版rrent_date_time"]||
// [elementName isEqualToString:@"condition"]||
// [elementName isEqualToString:@"humidity"]||
// [elementName isEqualToString:@"icon"]||
// [elementName isEqualToString:@"wind_condition"]||
// [elementName isEqualToString:@"low"]||
// [elementName isEqualToString:@"high"])
// {
// self.currentElement = [NSMutableString string];
// }
// else
// {
// self.currentElement = nil;
// }
if ([elementName isEqualToString:@"xml_api_reply"])
{
mWeather = [[TWeatherElement alloc]init];
NSString *data8= [attributeDict objectForKey:@"version"];
if(data8 !=nil)
mWeather.xmlapireply =data8 ;
[mParserArray addObject:data8];
}
if ([elementName isEqualToString:@"weather"])
{
NSString *data0= [attributeDict objectForKey:@"module_id"];
if(data0 !=nil)
mWeather.weather =data0 ;
NSLog(@"weather==%@",[attributeDict valueForKey:@"module_id"]);
}
if([elementName isEqualToString:@"current_date_time"])
{
NSString *data1= [attributeDict objectForKey:@"data"];
if (data1 !=nil)
mWeather.currentdate =data1;
NSLog(@"current_date_time==%@",[attributeDict valueForKey:@"data"]);
}
if([elementName isEqualToString:@"condition"])
{
NSString *data2= [attributeDict objectForKey:@"data"];
if (data2 !=nil)
mWeather.conditionname=data2;
NSLog(@"condition==%@",[attributeDict valueForKey:@"data"]);
}
if([elementName isEqualToString:@"humidity"])
{
NSString *data3= [attributeDict objectForKey:@"data"];
if (data3 !=nil)
mWeather.humidity =data3;
NSLog(@"humidity==%@",[attributeDict valueForKey:@"data"]);
}
if([elementName isEqualToString:@"icon "])
{
NSString *data4= [attributeDict objectForKey:@"data"];
if (data4 !=nil)
mWeather.icon =data4;
NSLog(@"icon==%@",[attributeDict valueForKey:@"data"]);
}
if([elementName isEqualToString:@"wind_condition "])
{
NSString *data5= [attributeDict objectForKey:@"data"];
if (data5 !=nil)
mWeather.wind =data5;
NSLog(@"wind_condition==%@",[attributeDict valueForKey:@"data"]);
}
if([elementName isEqualToString:@"low "])
{
NSString *data6= [attributeDict objectForKey:@"data"];
if (data6 !=nil) mWeather.mintemp = data6;
NSLog(@"low==%@",[attributeDict valueForKey:@"data"]);
}
if([elementName isEqualToString:@"high "])
{
NSString *data7= [attributeDict objectForKey:@"data"];
if (data7 !=nil) mWeather.maxtemp =data7;
NSLog(@"high==%@",[attributeDict valueForKey:@"data"]);
}
//{
//// 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 "])
{
mWeather.currentdate = self.currentElement;
}
else if ([elementName isEqualToString:@"condition "])
{
mWeather.conditionname = self.currentElement;
}
else if ([elementName isEqualToString:@"humidity "])
{
mWeather.humidity = self.currentElement;
}
else if ([elementName isEqualToString:@"icon "])
{
mWeather.icon = self.currentElement;
}
else if ([elementName isEqualToString:@"wind_condition "])
{
mWeather.wind = self.currentElement;
}
else if ([elementName isEqualToString:@"low "])
{
mWeather.mintemp = self.currentElement;
}
else if ([elementName isEqualToString:@"high "])
{
mWeather.maxtemp = self.currentElement;
}
else if ([elementName isEqualToString:@"weather"])
{
[mParserArray addObject:mWeather];
NSLog(@"mDataArray count = %d",[mParserArray count]);
[mWeather release];
}
}
//-(void)parserDidEndDocument:(NSXMLParser *)parser
//{
// [[NSNotificationCenter defaultCenter ]postNotificationName:kParsingFinishedNotification object:mParserArray];
//}
-(void)dealloc
{
[super dealloc];
self.weatherobj = nil;
self.currentElement = nil;
}
@end
this is controllerclass.h---------------------/
#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;
@end
this is controller class.m----------------------/
#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)
{
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];
}
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#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.
//TWeatherParser *parse = [[TWeatherParser alloc]init];
//weatherarray = parse.mParserArray;
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 = [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.reportdate.text = newobj.currentdate;
//cell.reportdate.text =@"My journey";
// cell.conditionname.text = @"raji";
// cell.twotemp.text = @"pradeep";
// cell.twodirection.text = @"harish";
// cell.humidity.text =@"23";
// cell.weatherimage.image = [UIImage imageNamed:@"listIcon-H.png"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#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
I don't know if it's intended, but what currently happening is:
When you find a predefined element (any you've named in an if-statement), you create an empty array (temp) and add your object in it. The XML parser then proceeds to the next element. In the next element, you empty your array and add that object.
So, in the end, only the LAST element found is added: xml_api_reply
Solution? Try to create an array in something like viewDidLoad
and do not create an empty array in every element, but add everything to an existing one (so: without creating an empty one and overwriting your existing array with it)
To make thing clear, using this code should do the trick:
-(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];
}
if([elementName isEqualToString:@"current_date_time"])
{
[mParserArray addObject:[attributeDict valueForKey:@"data"]];
}
if([elementName isEqualToString:@"condition"])
{
[mParserArray addObject:[attributeDict valueForKey:@"data"]];
}
if([elementName isEqualToString:@"humidity"])
{
[mParserArray addObject:[attributeDict valueForKey:@"data"]];
}
if([elementName isEqualToString:@"icon"])
{
[mParserArray addObject:[attributeDict valueForKey:@"data"]];
}
if([elementName isEqualToString:@"wind_condition"])
{
[mParserArray addObject:[attributeDict valueForKey:@"data"]];
}
if([elementName isEqualToString:@"low"])
{
[mParserArray addObject:[attributeDict valueForKey:@"data"]];
}
if([elementName isEqualToString:@"high"])
{
[mParserArray addObject:[attributeDict valueForKey:@"data"]];
}
The problem is in this part of the code
if([elementName isEqualToString:@"wind_condition"])
{
NSMutableArray *temp=[[NSMutableArray alloc]init];
self.mParserArray=temp;
[temp release];
[mParserArray addObject:[attributeDict valueForKey:@"data"]];
}
You need to create the array once and assign mParserArray(which should have retain property ) to it. Later you should keep adding objects to your mParserArray like
mParserArray addObject:[attributeDict valueForKey:@"data"]];
Do not create array and override them in every if statement.
Try the given below code:
- (void)viewDidLoad {
fcdayofweek = [[NSMutableArray alloc]init];
fclow = [[NSMutableArray alloc]init];
fchigh = [[NSMutableArray alloc]init];
fccondition = [[NSMutableArray alloc]init];
fcicon = [[NSMutableArray alloc]init];
NSString *url = [[NSString alloc]initWithString:@"http://www.google.com/ig/api?weather=,,,50500000,30500000"];
NSLog(@"%@",url);
NSURL *xmlURL = [[NSURL alloc]initWithString:url];
[url release];
//[[NSURLCache sharedURLCache] setMemoryCapacity:0];
//[[NSURLCache sharedURLCache] setDiskCapacity:0];
NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:xmlURL];
NSLog(@"Start parsing");
[xmlURL release];
[parser setDelegate:self];
[parser parse];
[parser release];
parser = nil;
[super viewDidLoad];
}
In your parser delgate method use the code:
/*------- prasing delegate methods ---------------*/
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Sorry!" message:@"Data is temporarily unavailable . Please try again in a few minutes." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// NSLog(@"found this element: %@", elementName);
if ([elementName isEqualToString:@"latitude_e6"]) {
NSLog(@"latitude ==%@",[attributeDict valueForKey:@"data"]);
// clear out our story item caches...
}
else if ([elementName isEqualToString:@"longitude_e6"])
{
NSLog(@"longitude==%@",[attributeDict valueForKey:@"data"]);
}
else if ([elementName isEqualToString:@"forecast_date"])
{
NSLog(@"forecastdate==%@",[attributeDict valueForKey:@"data"]);
}
else if ([elementName isEqualToString:@"current_date_time"])
{
NSLog(@"current_date_time===%@",[attributeDict valueForKey:@"data"]);
}
else if ([elementName isEqualToString:@"unit_system"])
{
NSLog(@"unit_system==%@",[attributeDict valueForKey:@"data"]);
}
else if ([elementName isEqualToString:@"temp_f"])
{
NSLog(@"temp_f==%@",[attributeDict valueForKey:@"data"]);
}
else if ([elementName isEqualToString:@"temp_c"])
{
NSLog(@"temp_c==%@",[attributeDict valueForKey:@"data"]);
}
else if ([elementName isEqualToString:@"humidity"])
{
NSLog(@"humidity==%@",[attributeDict valueForKey:@"data"]);
}
else if ([elementName isEqualToString:@"wind_condition"])
{
NSLog(@"wind_condition==%@",[attributeDict valueForKey:@"data"]);
}
else if ([elementName isEqualToString:@"day_of_week"])
{
[fcdayofweek addObject:[attributeDict valueForKey:@"data"]];
}
else if ([elementName isEqualToString:@"low"])
{
[fclow addObject:[attributeDict valueForKey:@"data"]];
}
else if ([elementName isEqualToString:@"high"])
{
[fchigh addObject:[attributeDict valueForKey:@"data"]];
}
else if ([elementName isEqualToString:@"icon"])
{
[fcicon addObject:[attributeDict valueForKey:@"data"]];
}
else if ([elementName isEqualToString:@"condition"])
{
[fccondition addObject:[attributeDict valueForKey:@"data"]];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
//NSLog(@"ended element: %@", elementName);
if ([elementName isEqualToString:@"Price"]) {
// save values to an item, then store that item into the array...
//NSLog(@"adding story: %@", currentTitle);
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@"found characters: %@", string);
// save the characters for the current item...
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"all done!");
//[self performSelectorOnMainThread:@selector(finishedparsing) withObject:nil waitUntilDone:NO];
}
精彩评论