2013-12-23 40 views
5

我不知道是否有可能使用jsoup例如變更取消註釋html標籤,取消註釋HTML標籤:如何使用jsoup

<!--<p> foo bar </p>--> 

<p> foo bar </p> 

回答

7

是的,它是可能的。這是解決這個的一種方法:

  1. 找到所有註釋節點
  2. 對於每個註釋中提取數據屬性
  3. 插入一個新的節點與數據當前註釋節點
  4. 後刪除註釋節點

看一看這段代碼:

public class UncommentComments { 
     public static void main(String... args) { 
      String htmlIn = "<html><head></head><body>" 
        + "<!--<div> hello there </div>-->" 
        + "<div>not a comment</div>" 
        + "<!-- <h5>another comment</h5> -->" 
        + "</body></html>"; 
      Document doc = Jsoup.parse(htmlIn); 
      List<Comment> comments = findAllComments(doc); 
      for (Comment comment : comments) { 
       String data = comment.getData(); 
       comment.after(data); 
       comment.remove(); 
      } 
      System.out.println(doc.toString()); 
     } 

     public static List<Comment> findAllComments(Document doc) { 
      List<Comment> comments = new ArrayList<>(); 
      for (Element element : doc.getAllElements()) { 
       for (Node n : element.childNodes()) { 
        if (n.nodeName().equals("#comment")){ 
         comments.add((Comment)n); 
        } 
       } 
      } 
      return Collections.unmodifiableList(comments); 
     } 
    } 

鑑於這種HTML文檔:

<html> 
    <head></head> 
    <body> 
    <!--<div> hello there </div>--> 
    <div>not a comment</div> 
    <!-- <h5>another comment</h5> --> 
    </body> 
</html> 

會導致這樣的輸出:

<html> 
    <head></head> 
    <body> 
    <div>hello there</div> 
    <div>not a comment</div> 
    <h5>another comment</h5> 
    </body> 
</html> 
+0

評論類,這是關鍵。 –