2011-09-24 21 views

答えて

30

基本的にはElements.select(selector)となります。selectorthis APIとなります。ただし、コメントは技術的に要素ではないので、ここでは混乱するかもしれませんが、ノード名は#commentです。

のは、それがうまくいくかもしれない方法を見てみましょう:うーん、これは私に与えている良いこと

import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Node; 

public class RemoveComments { 
    public static void main(String... args) { 
     String h = "<html><head></head><body>" + 
      "<div><!-- foo --><p>bar<!-- baz --></div><!--qux--></body></html>"; 
     Document doc = Jsoup.parse(h); 
     removeComments(doc); 
     doc.html(System.out); 
    } 

    private static void removeComments(Node node) { 
     for (int i = 0; i < node.childNodesSize();) { 
      Node child = node.childNode(i); 
      if (child.nodeName().equals("#comment")) 
       child.remove(); 
      else { 
       removeComments(child); 
       i++; 
      } 
     } 
    }   
} 
+0

を削除タイプエラー – user1893354

+1

あなたがJsoupの6年前のバージョンを手に入れることができれば、それは元に戻りました。それ以外の場合は、APIが更新されている場合は、この例を更新するための修正を歓迎します。 childNodesリストがいくつかのバージョンでは変更不可能になっているようです。 – dlamblin

-1

とこのコードの動作

doc.select("#comment").remove(); 

とコードにより多くのタグ

doc.select("script, style, meta, link, comment, CDATA, #comment").remove(); 
+1

'doc.select("#comment ")。remove();'は動作しません.HTMLコメントは削除されません。それはあなたのために働いたのですか? – yetanothercoder

+3

'doc.select("#comment ")。remove()は、" idフィールドが 'comment'と等しいノードをすべて削除することを意味します。 – Stephan

関連する問題