【问题标题】:How to parse HTML with TouchXML or some other alternative如何使用 TouchXML 或其他替代方法解析 HTML
【发布时间】: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。

&lt;div id="groupinfo-l"&gt;Person&lt;/div&gt;&lt;div id="groupinfo-r"&gt;Ralph&lt;/div&gt;

【问题讨论】:

    标签: iphone objective-c c xml parsing


    【解决方案1】:

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

    【讨论】:

    • 我尝试过 Element Parser,但无法获取某些数据。例如,假设我正在尝试获取“groupURL”链接的文本。我似乎无法得到它。我可以很好地获取 URL,但不能只获取链接的组 URL 标题。这是我的代码: Element* aTag = [document selectElement: @"a"]; NSString* href = [aTag 属性:@"href"]; NSLog(@"%@", href);
    • 我不在我的mac上,所以我不能给你确切的代码,但是如果你想获取“groupURL”元素的文本,你应该调用 [yourElement contentsText] 或 [yourElement getChildsContentsText:@"你的孩子"]。试试其中一个,反正明天我就能给你确切的解决方案。
    • 谢谢你的小费,我看看能不能得到文本。如果你不介意的话,如果你记得的话,你明天还能发布确切的代码。谢谢
    猜你喜欢
    • 2011-12-12
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多