2015-01-01 56 views
3

我想添加一個<div class="wrapper">我身體標記後生成的HTML。我想結束</div>在結束</body>之前。到目前爲止,我有JSoup添加包裝div後身體

private String addWrapper(String html) { 
    Document doc = Jsoup.parse(html); 
    Element e = doc.select("body").first().appendElement("div"); 
    e.attr("class", "wrapper"); 

    return doc.toString(); 
} 

和我得到

</head> 
    <body> 
    &lt;/head&gt; 
    <p>Heyo</p> 
    <div class="wrapper"></div> 
</body> 
</html> 

我也想不通爲什麼我的HTML越來越「< /頭>」了。我只有在使用JSoup時才能得到它。

回答

4

Jsoup Document使用標準化方法規範文本。 The method is here in Document class.所以它包裹和標籤。在Jsoup.parse()方法中,它可以接受三個參數:parse(String html,String baseUri,Parser parser);

我們將解析器參數設置爲使用XMLTreeBuilder的Parser.xmlParser(否則它使用HtmlTreeBuilder並且它將html標準化)。

我試過了,最新的代碼(也可能是優化):

String html = "<body>&lt;/head&gt;<p>Heyo</p></body>"; 

    Document doc = Jsoup.parse(html, "", Parser.xmlParser()); 

    Attributes attributes = new Attributes(); 
    attributes.put("class","wrapper"); 

    Element e = new Element(Tag.valueOf("div"), "", attributes); 
    e.html(doc.select("body").html()); 

    doc.select("body").html(e.toString()); 

    System.out.println(doc.toString()); 
+0

這工作!謝謝!! – CodeMinion