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

來源:互聯網
上載者:User

 

使用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

 

範例程式碼:

 

<br />#import "TFHpple.h"</p><p>NSData *data = [[NSData alloc] initWithContentsOfFile:@"example.html"];</p><p>// Create parser<br />xpathParser = [[TFHpple alloc] initWithHTMLData:data];</p><p>//Get all the cells of the 2nd row of the 3rd table<br />NSArray *elements = [xpathParser search:@"//table[3]/tr[2]/td"];</p><p>// Access the first cell<br />TFHppleElement *element = [elements objectAtIndex:0];</p><p>// Get the text within the cell tag<br />NSString *content = [element content]; </p><p>[xpathParser release];<br />[data release];<br />  

 

另外,還有一個類似的解決方案可以參考
ElementParser http://github.com/Objective3/ElementParser

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.