我正试图从这个xml中提取标题:
<entry>
...
<title type="html">Some title</title>
<published>2011-02-07T00:04:16Z</published>
<updated>2011-02-07T00:04:16Z</updated>
...
</entry>
在NSXMLParsing的didStartElement
代码中:
if ([elementName isEqualToString:@"entry"])
{
item = [[NSMutableDictionary alloc] init];
}
if([elementName isEqualToString:@"title"])
{
currentElement = [elementName copy];
currentTitle = [[NSMutableString alloc] init];
}
foundCharacters
中的:
if ([currentElement isEqualToString:@"title"])
{
[currentTitle appendString:string];
}
didEndElement
中的:
if ([elementName isEqualToString:@"entry"])
{
[item setObject:currentTitle forKey:@"title"];
[currentElement release];
currentElement = nil;
[item release];
item = nil;
}
问题在于,由于某种原因,当它到达didEndElement
时,currentTitle
已经获得了三个节点的内容,因此它的:
一些 title2011-02-07T00:04:16Z2011-02-07T00:04:16Z
我不明白为什么它选择已发布和更新的节点并将它们附加到标题字符串。
答案 0 :(得分:2)
您在currentElement
中将@"title"
设置为didStartElement:
,但您从未取消它。此特定XML文件中的第一个元素是title
,因此您设置currentElement
,然后为每个foundCharacters:
添加它们。将didStartElement:
更改为:
currentElement = [elementName copy];
if ([elementName isEqualToString:@"entry"])
{
item = [[NSMutableDictionary alloc] init];
}
if([elementName isEqualToString:@"title"])
{
currentTitle = [[NSMutableString alloc] init];
}
答案 1 :(得分:1)
你必须添加到didEndElement:
if ([elementName isEqualToString:@"title"])
{
[currentElement release];
currentElement = nil;
}
答案 2 :(得分:0)
定义 NSMutableString * strFoundCharacters;在类方法集属性中并合成它。
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *) string {
NSString *strAppend = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([strAppend length] > 0) {
[self.strFoundCharacters appendString:string];
}
}
将
中的strfoundcharacter设为nil - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"title"] ) {
self.currentTitle = self.strFoundCharacters;
}
[self.strFoundCharacters setString:@""];
}
我认为它会起作用