这是我需要解析的 XML 数据
<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>
这是我的 SCMessages.h 文件
#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;
这是我的 SCMessages.m 文件
#import "SCMessages.h"
@implementation SCMessages
@synthesize Date;
@synthesize Message,GroupName;
- (void)dealloc
{
[super dealloc];
[Date release];
[Message release];
[GroupName release];
}
@end
我使用下面的代码使用NSXMLParser
委托方法解析数据
#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;
}
}
问题 我没有得到所需的带有日期、消息和组名的消息对象。
我把NSLog
它们打印出来,但我总是得到空值。奇怪的是消息数组被分配了内存并且元素也被添加到数组中,因为我可以看到消息数组计数NSLog
但数组元素的数据为空值。
我正在解析在 NSURLConnection 委托方法中的 SOAP 响应中收到的 XML 数据connectionDidFinishLoading
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSLog(@"theXML: \n%@",theXML);