应该用什么测试来获取嵌套元素

时间:2013-07-20 15:17:03

标签: ios nsxmlparserdelegate

在这种情况下,标题存在于entry之前和之后的两次出现中:

<feed xmlns:im="http://xxx.com/rss" xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
    <id>http://xxxxx/xml</id><title>xxxxx: Top articles</title><updated>2013-07-20T04:30:05-07:00</updated><link rel="alternate" type="text/html" href="https://xxxx;popId=1"/><link rel="self" href="http://xxxxxxx/xml"/><icon>http://xxxxxxxxxxx</icon><author><name>xxxxxxx</name><uri>http://www.xxxxx.com/xxxxx/</uri></author><rights>Copyright 2001</rights>

        <entry>
            <updated>2013-07-20T04:30:05-07:00</updated>

                <id im:id="621507457">https://xxxxx.xxxx.com/us/album/blurred-lines-feat.-t.i.-pharrell/id621507456?i=621507457&amp;uo=2</id>
                 //I want to get only the title nested in entry tree
                <title>Robin Thicke</title>

为了逃避didStartElement:以外的任何问题,应该在<entry></entry>协议方法中进行哪些测试?

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict{

    if ([elementName isEqualToString:@"title"]) {
      //This is not enough, since it bring also the title value which is outside the entry tree
    }
}

我不想依赖像TBXML这样的外部库,我想知道这在纯NSXMLParserDelegate中是否可行?

1 个答案:

答案 0 :(得分:0)

您必须跟踪解析器当前是否在“entry元素内部”。 例如,你可以 在类中添加一个整数属性entryLevel, 最初设置为零  并在didStartElement中更新 和didEndElement

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"entry"]) {
        self.entryLevel++;
    } else if ([elementName isEqualToString:@"title"] && self.entryLevel > 0) {
        // title inside entry
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"entry"]) {
        self.entryLevel--;
    }
}