这是我的应用的代码。应用程序运行但没有显示数据,您能帮我解决这个问题吗?
在.h文件中:
@interface MyData : NSObject <NSXMLParserDelegate> {
NSMutableString *currentElementValue;
User *user;
NSMutableArray *users;
}
-(MyData *) initXMLParser;
-(BOOL)parseDocumentWithData:(NSData *)data;
@property (nonatomic, retain) User *user;
@property (nonatomic, retain) NSMutableArray *users;
在.m文件中:
@implementation MyData
@synthesize user;
@synthesize users;
- (MyData *) initXMLParser {
[super init];
// init array of user objects
users = [[NSMutableArray alloc] init];
return self;
}
-(BOOL)parseDocumentWithData:(NSData *)data {
NSString * filePath = [[NSBundle mainBundle] pathForResource:@"Users" ofType:@"xml"];
data = [NSData dataWithContentsOfFile:filePath];
if (data == nil)
return NO;
// this is the parsing machine
NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithData:data];
// this class will handle the events
[xmlparser setDelegate:self];
[xmlparser setShouldResolveExternalEntities:NO];
// now parse the document
BOOL ok = [xmlparser parse];
if (ok == NO)
NSLog(@"error");
else
NSLog(@"OK");
[xmlparser release];
return ok;
}
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:@"user"]) {
NSLog(@"user element found – create a new instance of User class...");
user = [[User alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (!currentElementValue) {
// init the ad hoc string with the value
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
// append value to the ad hoc string
[currentElementValue appendString:string];
}
NSLog(@"Processing value for : %@", string);
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:@"users"]) {
// We reached the end of the XML document
return;
}
if ([elementName isEqualToString:@"user"]) {
// object to our user array
[users addObject:user];
// release user object
[user release];
user = nil;
} else {
[user setValue:currentElementValue forKey:elementName];
}
[currentElementValue release];
currentElementValue = nil;
}
@end
/* This is the code of my app . The applications runs but there is no data displayed , can you help me to fix this problem ? */
这是我的应用的代码。应用程序运行但没有显示数据,你能帮我解决这个问题吗?我想在解析时显示数据
答案 0 :(得分:0)
如果您使用的是NSXML解析器(objective-c),则需要将解析xml元素的数据附加到字符串中。您打算如何显示xml文件中的数据。
您可以从这里应用相同的方法:
然后将解析器中的值更改为元素值。