【发布时间】:2010-12-19 17:22:53
【问题描述】:
我正在尝试使用 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,但我需要知道如何从以下示例中提取人名,在本例中为 Ralph。
<div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div>
【问题讨论】:
标签: iphone objective-c c xml parsing