这是我第一次使用XML,但我正在尝试使用NSXMLParser来解析我学校的日历XML(可以看到here)。
出于我的目的,我只需要在项目的标题和描述标签之间获取文本。
通过我在mac开发人员库中读到的内容,似乎解析器每次遇到一个元素(使用parser:didStartElement:namespaceURI:qualifiedName:attribute:
方法)时都会向委托发送通知,并且当它遇到文本时(使用{ {1}}方法)。虽然我可以看到你如何只使用didStartElement ...方法为某些元素做事情,但我看不出如何使用foundCharacters:方法只为我想要的某些元素获取文本。有没有办法做到这一点,或者我是以错误的方式解决这个问题?感谢。
答案 0 :(得分:2)
您无法阻止foundCharacters
被调用,但如果didStartElement
是您关注的两个元素之一,则可以elementName
设置一些类属性,然后让foundCharacters
查看该类属性以确定它是否应该对这些字符执行某些操作,或者是否应该立即返回并有效地丢弃它收到的字符。
例如,这是我的解析器的简化版本:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
// if the element name is in my NSArray of element names I care about ...
if ([self.elementNames containsObject:elementName])
{
// then initialize the variable that I'll use to collect the characters.
self.elementValue = [[NSMutableString alloc] init];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
// if the variable to collect the characters is not nil, then append the string
if (self.elementValue)
{
[self.elementValue appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
// if the element name is in my NSArray of element names I care about ...
if ([self.elementNames containsObject:elementName])
{
// step 1, save the data in `elementValue` here (do whatever you want here)
// step 2, reset my elementValue variable
self.elementValue = nil;
}
}
希望这能为您提供这个想法。