2013-11-05 39 views
3

如何使用Jsoup從html元素中刪除所有內聯樣式和其他屬性(class,onclick)?如何使用Jsoup從html元素中刪除所有內聯樣式和其他屬性?

樣品輸入:

<div style="padding-top:25px;" onclick="javascript:alert('hi');"> 
This is a sample div <span class='sampleclass'> This is a sample span </span> 
</div> 

樣本輸出:

<div>This is a sample div <span> This is a sample span </span> </div> 

我的代碼(?難道這是一個正確的方式或任何其他更好的方法是存在的)

Document doc = Jsoup.parse(html); 
Elements el = doc.getAllElements(); 
for (Element e : el) { 
    Attributes at = e.attributes(); 
    for (Attribute a : at) {  
     e.removeAttr(a.getKey());  
    } 
} 
+0

@ T.J.Crowder感謝您的答覆。看到我更新的問題。這是一種正確的方式還是其他更好的方法? – vjy

+0

@vjy更新的代碼是否適合您?還是還沒有工作? – ashatte

+0

@ashatte我找到了工作代碼並在問題中進行了更新。我想知道我正在做的是正確的還是其他更好的API,而不是遍歷所有元素來清除屬性? – vjy

回答

7

是,一種方法的確是遍歷元素並且調用removeAttr();

另一種使用jsoup的方法是利用Whitelist類(請參閱docs),該類可以與Jsoup.clean()函數一起使用,以從文檔中刪除任何非指定的標記或屬性。

例如:

String html = "<html><head></head><body><div style='padding-top:25px;' onclick='javascript.alert('hi');'>This is a sample div <span class='sampleclass'>This is a simple span</span></div></body></html>"; 

Whitelist wl = Whitelist.simpleText(); 
wl.addTags("div", "span"); // add additional tags here as necessary 
String clean = Jsoup.clean(html, wl); 
System.out.println(clean); 

會導致下面的輸出:

11-05 19:56:39.302: I/System.out(414): <div> 
11-05 19:56:39.302: I/System.out(414): This is a sample div 
11-05 19:56:39.302: I/System.out(414): <span>This is a simple span</span> 
11-05 19:56:39.302: I/System.out(414): </div> 
+0

謝謝..這是我需要的:-) – vjy

+0

沒問題,很高興幫助:) – ashatte

相關問題