关于ios:NSXMLParser-仅需要从parser:foundCharacters:中读取某些元素

NSXMLParser - only need to read from parser:foundCharacters: in certain elements

这是我第一次使用XML,但是我试图使用NSXMLParser来解析我学校的日历XML(可以在这里看到)。

出于我的目的,我只需要获取商品的标题和描述标签之间的文本。

通过我在Mac开发人员库中阅读的内容,似乎解析器每次碰到元素(使用parser:didStartElement:namespaceURI:qualifiedName:attribute:方法)和碰到文本(使用parser:foundCharacters:时)都会向委托发送通知。方法)。虽然我可以看到您只能使用didStartElement ...方法来仅对某些元素执行操作,但是我看不到如何仅可以针对所需的某些元素使用foundCharacters:方法来获取文本。有什么办法可以做到这一点,还是我会以错误的方式去做呢?谢谢。


您不能阻止foundCharacters被调用,但是如果elementName是您关心的两个元素之一,则可以让didStartElement设置一些类属性,然后让foundCharacters查看该类属性,以确定是否应该对那些字符进行处理,或者是否应该立即返回并有效地丢弃接收到的字符。

例如,这是我的解析器的简化版本:

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;
    }
}

希望这能给你这个主意。