我正在使用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];
}
答案 0 :(得分: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];
答案 1 :(得分: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]];
...