首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用TFHpple获取子数组的属性?

如何使用TFHpple获取子数组的属性?
EN

Stack Overflow用户
提问于 2010-09-04 00:49:32
回答 2查看 1.8K关注 0票数 0

我使用TFHpple (它使用XPath)来解析一个超文本标记语言文档。我可以获得各种节点的内容,等等。但是我在GitHub上找到的代码似乎不完整。它有一个方法来获取节点的属性,而不是子数组。所以我写了一个,但失败了。下面的两个“属性”方法可以很好地工作。基本上,我希望获得作为新节点的子数组。我认为我在NSDictionary级别上失败了。我试图从我在下面的“孩子”中返回的内容中创建一个新的TFHppleElement,但是……失败!有什么线索吗?

这来自TFHppleElement.m:

代码语言:javascript
复制
- (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];
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-09-08 10:41:43

我想我做得足够好了。但我最终将获得子节点数组的过程简化为:

代码语言:javascript
复制
- (NSDictionary *) children
{
    if ([self hasChildren])
        return [[node objectForKey: TFHppleNodeChildArrayKey] objectAtIndex: 0];
    return nil;
}

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

代码语言:javascript
复制
TFHppleElement *parentNode;
.
.
.
TFHppleElement *childNode = [[[TFHppleElement alloc] initWithNode: [parentNode children]] autorelease];
票数 0
EN

Stack Overflow用户

发布于 2011-04-12 01:42:17

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

代码语言:javascript
复制
- (NSDictionary *)children
{
    return [[node objectForKey:@"nodeChildArray"] objectAtIndex:0];
}

然后,当你需要孩子的时候:

代码语言:javascript
复制
...
FHppleElement *rowAtIndex = [xpathParser at:[NSString stringWithFormat:oddRowAtIndex,ii,x]];
...
...
TFHppleElement *children = [[TFHppleElement alloc] initWithNode:[rowAtIndex children]];
...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3637831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档