NSXMLParser - only need to read from parser:foundCharacters: in certain elements
这是我第一次使用XML,但是我试图使用NSXMLParser来解析我学校的日历XML(可以在这里看到)。
出于我的目的,我只需要获取商品的标题和描述标签之间的文本。
通过我在Mac开发人员库中阅读的内容,似乎解析器每次碰到元素(使用
您不能阻止
例如,这是我的解析器的简化版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | - (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; } } |
希望这能给你这个主意。