I am trying to extract the title from this xml:
<entry>
...
<title type="html">Some title</title>
<published>2011-02-07T00:04:16Z</published>
<updated>2011-02-07T00:04:16Z</updated>
...
</entry>
in the NSXMLParsing's didStartElement
code:
if ([elementName isEqualToString:@"entry"])
{
item = [[NSMutableDictionary alloc] init];
}
if([elementName isEqualToString:@"title"])
{
currentElement = [elementName copy];
currentTitle = [[NSMutableString alloc] init];
}
in foundCharacters
:
if ([currentElement isEqualToString:@"title"])
{
[currentTitle appendString:string];
}
in didEndElement
:
if ([elementName isEqualToString:@"entry"])
{
[item setObject:current开发者_运维百科Title forKey:@"title"];
[currentElement release];
currentElement = nil;
[item release];
item = nil;
}
The problem is that for some reason when it gets to the didEndElement
the currentTitle
has got the three node's content, so its:
Some title2011-02-07T00:04:16Z2011-02-07T00:04:16Z
I don't get why its picking up the published and updated node and appending them to the title string.
You set currentElement
to @"title"
in didStartElement:
but you never unset it. The first element in this particular XML file is title
, so you set currentElement
and for every foundCharacters:
thereafter you append them. Change didStartElement:
to:
currentElement = [elementName copy];
if ([elementName isEqualToString:@"entry"])
{
item = [[NSMutableDictionary alloc] init];
}
if([elementName isEqualToString:@"title"])
{
currentTitle = [[NSMutableString alloc] init];
}
You have to add to didEndElement:
if ([elementName isEqualToString:@"title"])
{
[currentElement release];
currentElement = nil;
}
define NSMutableString *strFoundCharacters; in class method set property and synthesize it. then in
- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *) string {
NSString *strAppend = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([strAppend length] > 0) {
[self.strFoundCharacters appendString:string];
}
}
make nil to strfoundcharacter in
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
if ([elementName isEqualToString:@"title"] ) {
self.currentTitle = self.strFoundCharacters;
}
[self.strFoundCharacters setString:@""];
}
i think it will work
精彩评论