【问题标题】:How do you get the attributes of a Child Array using TFHpple?如何使用 TFHpple 获取子数组的属性?
【发布时间】:2010-09-03 16:49:31
【问题描述】:

我正在使用 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];
}

【问题讨论】:

  • XPath 表达式相关问题在哪里?
  • TFHpple 使用 XPath 进行初始 HTML 解析。如果您使用过它,那么您知道您可以获得节点的内容、名称和属性。我想要子数组。我的尝试失败了。希望有人对 TFHpple(和 NSDictionaries/Obj-C)有足够的了解,以了解为什么我的 children 方法不起作用。

标签: attributes children hpple


【解决方案1】:

我想我做得很好。但我最终将子节点数组简化为:

- (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];

【讨论】:

    【解决方案2】:

    将以下内容添加到您的 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]];
    ...
    

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 2016-04-03
      • 1970-01-01
      • 2014-04-03
      • 2021-12-11
      • 2013-06-01
      • 2017-03-15
      • 2019-05-12
      • 1970-01-01
      相关资源
      最近更新 更多