我试图解析下面用TouchXML呈现的HTML,但是当我尝试提取某些属性时它会一直崩溃。我对解析器世界完全陌生,因此对于成为一名完全白痴而道歉。我需要帮助来解析这个HTML。我试图完成的是解析每个属性和值或不是什么,并将它们复制到一个字符串。我一直在试图找到一个很好的解析器来解析HTML,我相信TouchXML是我见过的最好的,因为Tidy。说起Tidy,我怎么能通过Tidy先运行这个HTML然后解析它?我不知道如何做到这一点。这里是我迄今为止没有用的代码,因为它没有从HTML中提取我需要的所有东西。任何帮助或建议将不胜感激。由于如何使用TouchXML或其他替代方法解析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>
编辑:我可以用元素分析器,但我需要知道如何从中提取这个人的名字在这种情况下,下面的例子将是Ralph。
<div id="groupinfo-l">Person</div><div id="groupinfo-r">Ralph</div>
我试过元素分析器,但我无法获得某些数据。例如,假设我正在尝试获取“groupURL”链接的文本。我似乎无法得到它。我可以很好地获取URL,但我无法获取链接的组URL标题。这是我的代码:\t Element * aTag = [document selectElement:@“a”]; \t NSString * href = [aTag属性:@“href”]; NSLog(@“%@”,href); – 0SX 2010-12-19 17:51:51
我不在我的Mac上,所以我不能给你确切的代码,但是如果你想获得“groupURL”元素的文本,你应该调用[yourElement contentsText]或[yourElement getChildsContentsText:@“your child” ]。无论如何,尝试与他们中的一个,明天我将能够给你准确的解决方案。 – ender 2010-12-19 18:41:05
感谢您的提示,我会看看我是否可以获取文本。如果你还记得,如果你不介意,明天你还可以发布确切的代码。谢谢 – 0SX 2010-12-19 19:40:34