我正在创建一个需要阅读XML file
的iPhone应用@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *fileName;
@property (nonatomic, strong) NSString *description;
@property (nonatomic, strong) NSString *date;
@property (nonatomic, strong) NSString *link;
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
// FIRST TAG XML
if([elementName isEqualToString:@"title"]){
// GET DATA FROM XML
getData = YES; // getData is a bool which is NO initialy
NSLog(@"Found");
}
else
NSLog(@"Not Found");
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(getData)
{
// CREATION DE L OBJET DEPUIS LE XML
NSLog(@"This is your desired data = %@",string);
NSLog(@"Object creation ...");
Pebkac *peb = [[Pebkac alloc] init];
NSLog(@"Setup the name ...");
[peb setName:@"Pebkac"];
NSLog(@"Small descrption ...");
[peb setDescription:string];
[pebkacs addObject:peb];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
// XML END TAG
if ([elementName isEqualToString:@"title"]){
getData = NO;
}
}
我观察到的错误是,有时它不能获得标签之间的所有文本。
答案 0 :(得分:6)
foundChars
可以被调用N次。您总是将字符串设置为您到达的字符。你必须一次又一次地附加字符,当你接到endTag
电话时,你必须设置结果。
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
if(!foundChars)
foundChars = [[NSMutableString alloc] init];
[foundChars appendString:string];
}
然后在最后使用它 - 示例是为了适合您的问题而编写的
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if(getData)
{
// CREATION DE L OBJET DEPUIS LE XML
NSLog(@"This is your desired data = %@",string);
NSLog(@"Object creation ...");
Pebkac *peb = [[Pebkac alloc] init];
NSLog(@"Setup the name ...");
[peb setName:@"Pebkac"];
NSLog(@"Small descrption ...");
[peb setDescription:foundChars];
[pebkacs addObject:peb];
}
//reset
foundChars = nil;
// XML END TAG
if ([elementName isEqualToString:@"title"]){
getData = NO;
}
}
答案 1 :(得分:0)
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
每个元素可以多次调用。每次为每个标记调用此方法时,您需要将string
附加在一起,然后将其设置在对象中:
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
参考此question/answer,了解如何正确使用NSXMLParser