0

我正在创建一个需要读取XML 文件的 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;
    }
}

我观察到的错误是,有时它无法获取标签之间的所有文本。

4

2 回答 2

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;
    }
}
于 2012-12-26T18:24:07.890 回答
0

方法

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

每个元素可以被多次调用。每次调用此方法时,您需要将string每个标签附加在一起,然后将其设置在对象上:

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

参考此问题/答案以获取有关如何正确完成使用的简明示例NSXMLParser

于 2012-12-26T18:23:22.387 回答