1

因此,我正在使用 HPPLE 在 iOS 应用程序中执行一些 Xpath 查询,该应用程序需要对一些站点进行一些基本的 Web 抓取。现在一切都很好,但我想看看是否有另一种更优雅的方式来做我正在做的事情。目前我正在做的是我正在使用 XPath 在网站中查找特定的 div 类,在该网站中(基本上就像一个帖子)可以有任意数量的具有文本的孩子,以及其他有文本的孩子埋在另一组孩子里。现在,我基本上使用重复的 For 循环来检查“文本”标签名是否存在,如果存在,则将该值添加到字符串中,如果不存在,则检查是否还有其他级别的子项需要扫描,我有 4 个级别到目前为止相同的搜索。

 for (TFHppleElement *element in searchNodes) {
    //If a Text Node is found add it to the String, if not search again with next layer
    if ([element.tagName isEqualToString:@"text"]) {
        [bigString appendString:element.content];
    }
    //1. First layer Scan
    if (element.children.count > 0) {
        for (TFHppleElement *nextStep in element.children) { 
            if ([nextStep.tagName isEqualToString:@"text"]) {
                [bigString appendString:nextStep.content];
            }
            
            //2. Second layer Scan
            if (nextStep.children.count > 0) {
                for (TFHppleElement *child in nextStep.children) { 
                    if ([child.tagName isEqualToString:@"text"]) {
                        [bigString appendString:child.content];
                        
                    }
                    
                    //3. Thrid Layer Scan
                    if (child.children.count > 0) {
                        for (TFHppleElement *children in child.children) { 
                            if ([children.tagName isEqualToString:@"text"]){
                                [bigString appendString:children.content];
                            }
                            
                            //4. Fourth Layer Scan
                            if (children.children.count > 0) {
                                for (TFHppleElement *newchild in children.children){
                                    if ([newchild.tagName isEqualToString:@"text"]) {
                                        [bigString appendString:newchild.content];
                                        
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

我想要某种方法构建,我基本上可以通过初始 NSArray 发送,然后它检查其他元素,然后使用下一个数组再次执行搜索,同时继续构建一个 NSMutableString 最终将每次搜索的所有文本。如果没有,我现在似乎工作正常,我只是想看看是否有更清洁的方法来做到这一点。

4

1 回答 1

0

我认为你想要的是递归。您可以编写一个将元素传递给的递归方法,让它在自身外部修改一些 NSMutableString(可能是一个实例变量?),然后children如果可以的话,用它自己的调用自身。例如(未编译,未经测试):

@property (nonatomic, retain) NSMutableString * bigString;
// snip
@synthesize bigString;
// snip - assume bigString gets initialized somewhere

- (void)checkElement:(TFHppleElement *)elem {
    if ([element.tagName isEqualToString:@"text"]) {
        [bigString appendString:elem.content];
    }

    if (element.children.count > 0) {
        for (TFHppleElement * child in element.children) {
            [self checkElement:child];
        }
    }
}
于 2012-07-11T22:30:46.113 回答