2015-01-01 27 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