2011-08-18 25 views
4

我正在爲android做一個應用程序,並且該應用程序的功能的一個元素是返回來自在線搜索庫的目錄的結果。應用程序需要以與應用程序其餘部分保持一致的方式顯示搜索結果,該搜索結果通過自定義HTML表單進行。即,搜索的結果需要被解析並顯示有用的元素。我只是想知道如何/如何可以在android中實現?如何在android中解析HTML?

回答

13

你會使用一個Html解析器。一個我使用和工作得很好的是JSoup 這是你需要從解析html開始的地方。另外Apache Jericho是另一個好的。

您將使用DOM檢索html文檔,並使用JSOUP Select()方法選擇您想要獲取的任何標籤。通過標籤,ID或類別。

解決方案

Use the: Jsoup.connect(String url) method: 

Document doc = Jsoup.connect("http://example.com/").get(); 

這將允許您通過使用URL連接到HTML頁面。並通過DOM將其存儲爲Document文檔。並使用selector()方法從它讀取。

說明

的連接(字符串URL)方法創建一個新的連接,並得到() 取和解析HTML文件。如果在獲取 URL時發生錯誤,則會拋出IOException,您應該適當地處理 。

連接接口是專爲法鏈打造 具體要求:

Document doc = Jsoup.connect("http://example.com") 

如果通過對Jsoup的文檔閱讀,你應該能夠做到這一點。

編輯:這裏是你將如何使用選擇方法

//Once the Document is retrieved above, use these selector methods to Extract the data you want by using the tags, id, or css class 

    Elements links = doc.select("a[href]"); // a with href 
    Elements pngs = doc.select("img[src$=.png]"); 
    // img with src ending .png 

    Element masthead = doc.select("div.masthead").first(); 
    // div with class=masthead 

    Elements resultLinks = doc.select("h3.r > a"); // direct a after h3 

編輯:使用JSOUP你可以使用它來獲取屬性,文本,

Document doc = Jsoup.connect("http://example.com") 
Element link = doc.select("a").first(); 

String text = doc.body().text(); // "An example link" 
String linkHref = link.attr("href"); // "http://example.com/" 
String linkText = link.text(); // "example"" 

String linkOuterH = link.outerHtml(); 
// "<a href="http://example.com"><b>example</b></a>" 
String linkInnerH = link.html(); // "<b>example</b>" 
+0

讓我知道,如果這有助於 – yoshi24

0

由於搜索結果是HTML和HTML是標記語言(ML),因此您可以使用Android的XmlPullParser解析結果。