This is my XML data that I need to parse
<GetMessagesResult>
<NewDataSet xmlns="">
<Table>
<Date>21:52:59</Date>
<Message>ABC</Message>
<GroupName>ALL</GroupName>
</Table>
<Table>
<Date>11:23:27</Date>
<Message>DEF</Message>
<GroupName>ALL</GroupName>
</Table>
</NewDataSet>
</GetMessagesResult>
This is my SCMessages.h file
#import <Foundation/Foundation.h>
@interface SCMessages : NSObject
{
NSDate *Date;
NSString *Message;
NSString *GroupName;
}
@property (nonatomic, retain) NSDate *Date;
@property (nonatomic, retain) NSString *Message;
@property (nonatomic, retain) NSString *GroupName;
and this is my SCMessages.m file
#import "SCMessages.h"
@implementation SCMessages
@synthesize Date;
@synthesize Message,GroupName;
- (void)dealloc
{
[super dealloc];
[Date release];
[Message release];
[GroupName release];
}
@end
I used below code to parse the data using NSXMLParser delegate methods
#pragma mark - NSXMLParser Delegate
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if( [elementName isEqualToString:@"GetMessagesResult"])
{
if(!soapResults)
soapResults = [[NSMutableString alloc] init];
recordResults = TRUE;
}
if([elementName isEqualToString:@"NewDataSet"]) {
//Initialize the array.
messages = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"Table"]) {
//Initialize the message.
aMessage = [[SCMessages alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if( recordResults )
[soapResults appendString: string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"Table"]) {
[messages addObject:aMessage];
NSLog(@"MESSAGES COUNT: %d",messages.count);
NSLog(@"MESSAGE: %@",aMessage);
[aMessage release];
aMessage = nil;
}
// as this is the last element
if( [elementName isEqualToString:@"NewDataSet"])
{
recordResults = FALSE;
}
}
PROBLEM I am not getting the desired message object with Date, Meesage & GroupName.
I put NSLog to print them but I always get null value. The weird thing is message array gets allocated memory & also elements gets added to array as I can see message array count in NSLog but the array element has data as null value.
I am parsing the XML data received in SOAP response in NSURLConnection delegate method connectionDidFinishLoading
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(@"theXML: \n%@",theXML);
You need to store your values in
aMessage. You have added particular object to array but you forgot to store data in that object of SCMessages class.You can also check while debug that you are getting value inaMessageobject.You need to store value like this in this
didEndElementmethod.I think this will help you.