Elton's Blog

Tag: HTML

如何使用Objective-C解析HTML和XML

by Elton on 2010年02月25日, under Mac

使用Objective-C解析HTML或者XML,系统自带有两种方式一个是通过libxml,一个是通过NSXMLParser。不过这两种方式都需要自己写很多编码来处理抓取下来的内容,而且不是很直观。

有一个比较好的类库hpple,它是一个轻量级的包装框架,可以很好的解决这个问题。它是用XPath来定位和解析HTML或者XML。

安装步骤:
-加入 libxml2 到你的项目中
Menu Project->Edit Project Settings
搜索 “Header Search Paths”
添加新的 search path “${SDKROOT}/usr/include/libxml2″
Enable recursive option

-加入 libxml2 library 到你的项目
Menu Project->Edit Project Settings
搜索 “Other Linker Flags”
添加新的 search flag “-lxml2″

-将下面hpple的源代码加入到你的项目中:
HTFpple.h
HTFpple.m
HTFppleElement.h
HTFppleElement.m
XPathQuery.h
XPathQuery.m

-XPath学习地址http://www.w3schools.com/XPath/default.asp

示例代码:

  1.  
  2. #import "TFHpple.h"
  3.  
  4. NSData *data = [[NSData alloc] initWithContentsOfFile:@"example.html"];
  5.  
  6. // Create parser
  7. xpathParser = [[TFHpple alloc] initWithHTMLData:data];
  8.  
  9. //Get all the cells of the 2nd row of the 3rd table
  10. NSArray *elements  = [xpathParser search:@"//table[3]/tr[2]/td"];
  11.  
  12. // Access the first cell
  13. TFHppleElement *element = [elements objectAtIndex:0];
  14.  
  15. // Get the text within the cell tag
  16. NSString *content = [element content];  
  17.  
  18. [xpathParser release];
  19. [data release];
  20.  

另外,还有一个类似的解决方案可以参考
ElementParser http://github.com/Objective3/ElementParser

9 Comments :, , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit my friends!

A few highly recommended friends...