如何使用TouchXML或其他替代方法解析HTML

时间:2010-12-19 17:22:54

标签: iphone objective-c c xml parsing

我正在尝试使用TouchXML解析下面提供的HTML,但是当我尝试提取某些属性时它会不断崩溃。我对解析器世界完全陌生,所以我为成为一个完全白痴而道歉。我需要帮助来解析这个HTML。我想要完成的是解析每个属性和值或不是什么,并将它们复制到一个字符串。我一直在努力找到一个解析HTML的好解析器,我相信TouchXML是我见过的最好的因为Tidy。说到Tidy,我怎么能先通过Tidy运行这个HTML然后再解析它?我不知道该怎么做。以下是我到目前为止无法使用的代码,因为它没有从HTML中提取我需要的所有内容。任何帮助或建议将不胜感激。感谢

我目前的代码:

NSMutableArray *res = [[NSMutableArray alloc] init];

//  using local resource file
NSString *XMLPath   = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"example.html"];
NSData *XMLData     = [NSData dataWithContentsOfFile:XMLPath];
CXMLDocument *doc   = [[[CXMLDocument alloc] initWithData:XMLData options:0 error:nil] autorelease];

NSArray *nodes = NULL;

nodes = [doc nodesForXPath:@"//div" error:nil];

for (CXMLElement *node in nodes) {
    NSMutableDictionary *item = [[NSMutableDictionary alloc] init];



    [item setObject:[[node attributeForName:@"id"] stringValue] forKey:@"id"];

    [res addObject:item];
    [item release];
}


NSLog(@"%@", res);
[res release];

需要解析的HTML文件:

<html> 
<head> 
<base target="_blank" /> 
</head> 
<body style="margin:2;"> 
<div id="group"> 
<div id="groupURL"><a href="http://www.example.com/groups">Group URL</a></div> 
<img id="grouplogo" src="http://images.example.com/groups/image.png" /> 
<div id="groupcomputer"><a href="http://www.example.com/groups/page" title="Group Title">Group title this would be here</a></div> 
<div id="groupinfos"> 
    <div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div> 
    <div id="groupinfo-l">Years</div><div id="groupinfo-r">4 years</div> 
    <div id="groupinfo-l">Salary</div><div id="groupinfo-r">100K</div> 
    <div id="groupinfo-l">Other</div><div id="groupoth" style="width:15px">other info</div> 
</body> 
</html>

编辑:我可以使用Element Parser,但我需要知道如何从以下示例中提取Person的名称,在这种情况下将是Ralph。

<div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div>

1 个答案:

答案 0 :(得分:1)

我不知道你做错了什么,但我建议你使用element parser,这是我发现的最好的XML和HTML解析器。希望这会有所帮助。