簡體   English   中英

Jsoup僅過濾掉一些從html到文本的標簽

[英]Jsoup filter out only some tags from html to text

jsoup的高手可以告訴我一些將html過濾為文本/字符串的建議嗎? 我試過調用Document的text()。 但是所有標簽/元素都會被過濾。 我的目的是過濾一些指定的標簽。

即:我有html文字,例如:

<div>hello<p>world</div>,<table><tr><td>xxx</td></tr>

得到結果:

<div>hello<p>world</div>,xxx 

其中已過濾標簽。

我現在無法測試,但是我想您想編寫一個遞歸函數,該函數逐步遍歷樹並根據條件打印每個節點。 以下是其外觀的示例,但我希望您必須對其進行修改以更精確地滿足您的需求。

Document doc = JSoup.parse(page_text);
recursive_print(doc.head());
recursive_print(doc.body());

...

private static Set<String> ignore = new HashSet<String>(){{
  add("table");
  ...
}};
public static void recursive_print(Element el){
   if(!ignore.contains(el.className()))
     System.out.println(el.html());
   for(Element child : el.children())
     recursive_print(child);
}

您可以使用Whitelist來實現此目標。 例如:

Whitelist whiteList = new Whitelist();
whiteList.addTags("div", "p", "td");

這意味着所有其他標簽將被刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM