我正在尝试解析以下XML文件:
然而,当我解析它时:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
currentElementName = elementName;
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([currentElementName isEqualToString:@"link"]) {
NSLog(@"Link: %@",string);
}
}
我得到以下NSLOG:
Link: http://www.flickr.com/photos/114014058@N06/
Link:
Link: http://www.flickr.com/photos/114014058@N06/
Link:
Link:
Link: http://www.flickr.com/photos/114014058@N06/11865861164/
Link:
如您所见,我想要的网址没有显示,并且有一堆空网址。
为什么?
谢谢!
编辑:
我尝试了Rhythmic Fistman的回答,但我得到的只是:
link is (null)
答案 0 :(得分:2)
尝试didStartElement
回调。
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
当elementName
为@"link"
时,您的网址应位于attributeDict[@"href"]
。
e.g。
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if([elementName isEqualToString:@"link"]) {
NSLog(@"link is %@\n", attributeDict[@"href"]);
}
}
答案 1 :(得分:0)
你会在didStartElement中找到元素启动,所以在那里改变状态。当你找到foundCharacters,检查你是否处于正确的状态,然后那里的字符就是你想要的。
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// assume currentElementName starts out nil. if we find "generator", enter
// "generator" state. if we're in "generator" state and find "link" then enter
// "link" state, which is our target state
if ([currentElementName isEqualToString:@"generator"] && [elementName isEqualToString:@"link"])
currentElementName = @"link";
// now we're in the tag we want to be in. get attributes from
// the attributeDict, if you need the tag body, check for "link" state in foundChars
NSLog(@"here are the attributes we want %@", attributeDict);
else if ([elementName isEqualToString:@"generator"]) {
currentElementName = @"generator";
}
}