0

我正在使用 TFHpple(它使用 XPath)来解析 HTML 文档。我可以得到各种节点的内容等。但是我在GitHub上找到的代码似乎不完整。它有一种方法来获取节点的属性,但子数组。所以我写了一个,失败了。下面的两种“属性”方法可以正常工作。基本上,我想将子数组作为新节点。我认为我在 NSDictionary 级别上失败了。我试图用我在下面的“孩子”中返回的内容制作一个新的 TFHppleElement,但是......失败了!有什么线索吗?

这是来自 TFHppleElement.m:

- (NSDictionary *) attributesForNode: (NSDictionary *) myNode
{
 NSMutableDictionary *translatedAttributes = [NSMutableDictionary dictionary];
 for (NSDictionary *attributeDict in [myNode objectForKey: TFHppleNodeAttributeArrayKey]) 
 {
  //NSLog(@"attributeDict: %@", attributeDict);
  [translatedAttributes setObject: [attributeDict objectForKey: TFHppleNodeContentKey]
         forKey: [attributeDict objectForKey: TFHppleNodeAttributeNameKey]];
 }
 return translatedAttributes;
}

- (NSDictionary *) attributes
{
 return [self attributesForNode: node];
}

- (BOOL) hasChildren
{
 return [node objectForKey: TFHppleNodeChildArrayKey] != nil;
}

- (NSDictionary *) children
{
 NSMutableDictionary *translatedChildren = [NSMutableDictionary dictionary];
 for (NSDictionary *childDict in [node objectForKey: TFHppleNodeChildArrayKey]) 
 {
  [translatedChildren setObject: childDict
          forKey: [childDict objectForKey: TFHppleNodeNameKey]];
 }
 return [node objectForKey: TFHppleNodeChildArrayKey];
}
4

2 回答 2

0

我想我做得够对了。但我最终将子节点数组简化为:

- (NSDictionary *) children
{
    if ([self hasChildren])
        return [[node objectForKey: TFHppleNodeChildArrayKey] objectAtIndex: 0];
    return nil;
}

我将此添加到我下载的 TFHppleElement.m 代码中。然后我可以获取该结果并创建一个新节点,我可以从中提取所需的任何属性或内容。:

TFHppleElement *parentNode;
.
.
.
TFHppleElement *childNode = [[[TFHppleElement alloc] initWithNode: [parentNode children]] autorelease];
于 2010-09-08T02:41:42.880 回答
0

将以下内容添加到您的 TFHppleElement 接口/实现中:

- (NSDictionary *)children
{
    return [[node objectForKey:@"nodeChildArray"] objectAtIndex:0];
}

然后,当您需要孩子时:

...
FHppleElement *rowAtIndex = [xpathParser at:[NSString stringWithFormat:oddRowAtIndex,ii,x]];
...
...
TFHppleElement *children = [[TFHppleElement alloc] initWithNode:[rowAtIndex children]];
...
于 2011-04-11T17:42:17.100 回答