2011-09-23 74 views
0

我有這個HTML我解析。如何解析HTML標題

<div id="articleHeader"> 
<h1 class="headline">Assassin's Creed Revelations: The Three Heroes</h1> 
<h2 class="subheadline">Exclusive videos and art spanning three eras of assassins.</h2> 
<h2 class="publish-date"><script>showUSloc=(checkLocale('uk')||checkLocale('au'));document.writeln(showUSloc ? '<strong>US, </strong>' : '');</script> 

<span class="us_details">September 22, 2011</span> 

我想這樣做,解析「標題」副標題和發佈日期都以獨立字符串

+0

看看這個以前問一個問題:http://stackoverflow.com/questions/2188049/parse-html-in-android – slayton

回答

2

只需使用正確的CSS selectors來抓住它們。

Document document = Jsoup.connect(url).get(); 
String headline = document.select("#articleHeader .headline").text(); 
String subheadline = document.select("#articleHeader .subheadline").text(); 
String us_details = document.select("#articleHeader .us_details").text(); 
// ... 

或者稍微更高效:

Document document = Jsoup.connect(url).get(); 
Element articleHeader = document.select("#articleHeader").first(); 
String headline = articleHeader.select(".headline").text(); 
String subheadline = articleHeader.select(".subheadline").text(); 
String us_details = articleHeader.select(".us_details").text(); 
// ... 
0

Android有一個SAX parser built into it什麼。您也可以使用其他標準XML解析器。

但我想如果你的HTML足夠簡單,你可以使用RegEx來提取字符串。

+0

正則表達式? * Shudder。*你錯過了'jsoup'標籤嗎? – BalusC

+0

是的,我確實想念jsoup,我喜歡RegEx – the100rabh

+0

我也喜歡正則表達式。但是,解析HTML?完全是錯誤的工具。 – BalusC