значение тега читается парсером дважды - PullRequest
1 голос
/ 11 августа 2011

Я пытаюсь проанализировать XML-файл, но не получаю подходящие проанализированные данные. Когда я получаю вывод в GDB, то я получаю двойное значение из тегов в XML-файле. вот мой код:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{            
//NSLog(@"found this element: %@", elementName);
currentElement = [elementName copy];
if ([elementName isEqualToString:@"item"]) {
    // clear out our story item caches...
    //item = [[NSMutableDictionary alloc] init];
    blogtitle = [[NSMutableString alloc] init];
    publishdate = [[NSMutableString alloc] init];
    creator = [[NSMutableString alloc] init];
    category = [[NSMutableString alloc] init];
    description = [[NSMutableString alloc] init];
    content = [[NSMutableString alloc] init];
}}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@"found characters: %@", string);
// save the characters for the current item...
if ( [currentElement isEqualToString:@"title"]) {
    [blogtitle appendString:string];
    NSLog(@"blogtitle....%@",blogtitle);
}else  if ([currentElement isEqualToString:@"pubDate"]) {
    [publishdate appendString:string];
    NSLog(@"publishdate....%@",publishdate);
}else  if ([currentElement isEqualToString:@"dc:creator"]) {
    [creator appendString:string];
    NSLog(@"creator....%@",creator);
}else  if ([currentElement isEqualToString:@"category"]) {
    [category appendString:string];
    NSLog(@"category....%@",category);
} if ([currentElement isEqualToString:@"description"]) {
    [description appendString:string];
    NSLog(@"description....%@",description);
} if ([currentElement isEqualToString:@"content:encoded"]) {
    [content appendString:string];
    NSLog(@"content....%@",content);
}
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
//NSLog(@"ended element: %@", elementName);
if ([elementName isEqualToString:@"item"]) {
    // save values to an item, then store that item into the array...
                [item setObject:blogtitle forKey:@"title"];
                [item setObject:publishdate forKey:@"pubDate"];
                [item setObject:creator forKey:@"dc:creator"];
                [item setObject:category forKey:@"category"];
                [item setObject:description forKey:@"description"];
                [item setObject:content forKey:@"content:encoded"];
                [arr addObject:[item copy]];
    //            NSLog(@"adding story: %@", currentTitle);
}

}

вывод в GDB:

2011-08-11 17:32:49.651 the-life-doctor[5282:207] blogtitle....(null)
2011-08-11 17:33:02.897 the-life-doctor[5282:207] blogtitle....(null)
2011-08-11 17:33:07.760 the-life-doctor[5282:207] description....(null)
2011-08-11 17:33:09.217 the-life-doctor[5282:207] description....(null)
2011-08-11 17:33:10.559 the-life-doctor[5282:207] publishdate....(null)
2011-08-11 17:33:11.769 the-life-doctor[5282:207] publishdate....(null)
2011-08-11 17:33:24.104 the-life-doctor[5282:207] blogtitle....WHERE DOES LOVE LIVE
warning: Attempting to create USE_BLOCK_IN_FRAME variable with block that isn't in the        frame.
warning: Attempting to create USE_BLOCK_IN_FRAME variable with block that isn't in the   frame.
2011-08-11 17:35:34.265 the-life-doctor[5282:207] blogtitle....WHERE DOES LOVE LIVE

2011-08-11 17:35:39.053 the-life-doctor[5282:207] publishdate....Mon, 22 Nov 2010   17:43:47 +0000
2011-08-11 17:35:40.146 the-life-doctor[5282:207] publishdate....Mon, 22 Nov 2010 17:43:47 +0000
2011-08-11 17:35:40.644 the-life-doctor[5282:207] creator....admin
2011-08-11 17:35:41.236 the-life-doctor[5282:207] creator....admin

2011-08-11 17: 35: 41.898 the-life-doctor [5282: 207] категория .... ГДЕ ЛЮБИТ ЖИТЬ 2011-08-11 17: 35: 42.341 категория «доктор жизни» [5282: 207] .... ГДЕ ЛЮБИТ ЖИТЬ

вот мой xml файл: enter image description here

Мне нужны значения из тега элемента, т. Е. Заголовка, pubDate, категории и т. Д., Но каждый раз значение выводится дважды. пожалуйста, помогите мне.

Ответы [ 2 ]

1 голос
/ 11 августа 2011

вместо добавления содержимого в строку, вы должны рассмотреть возможность установки значений в -

(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
}

поэтому код будет похож на

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//NSLog(@"found characters: %@", string);
// save the characters for the current item...
if ( [currentElement isEqualToString:@"title"]) {
    blogtitle = string;
    NSLog(@"blogtitle....%@",blogtitle);
}else  if ([currentElement isEqualToString:@"pubDate"]) {
    publishdate = string;
    NSLog(@"publishdate....%@",publishdate);
}...

}
1 голос
/ 11 августа 2011

Посмотрите документацию на http://developer.apple.com/library/ios/#documentation/cocoa/reference/NSXMLParserDelegate_Protocol/Reference/Reference.html. В частности, он говорит -

Объект синтаксического анализатора может отправить делегату несколько анализаторов: foundCharacters: сообщения для сообщения символов элемента. Поскольку строка может быть только частью общего символьного содержимого для текущего элемента, вы должны добавить его к текущему накоплению символов, пока элемент не изменится.NSLogs не проблема.Однако в вашем случае строка параметра имеет значение null (возможно, из-за ошибки синтаксического анализа).Вам следует добавлять строку только в том случае, если она не равна нулю.

HTH,

Акшай

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...