CodeMinion
CodeMinion

Reputation: 111

JSoup Add Wrapper div after body

I am trying to add a <div class="wrapper"> to my generated html after the body tag. I want the ending </div> to be before the ending </body>. So far I have

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();
}

and I am getting

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

I also can't figure out why I am getting "</head>" in the html too. I only get it when I use JSoup.

Upvotes: 3

Views: 1591

Answers (1)

İlker Korkut
İlker Korkut

Reputation: 3250

Jsoup Document normalizes the text with normalise method. The method is here in Document class. So It wraps with and tags.

In Jsoup.parse() method it can take three parameter, parse(String html, String baseUri, Parser parser);

We will give the parser parameter as Parser.xmlParser which is using XMLTreeBuilder (Otherwise it uses HtmlTreeBuilder and it normalises html.).

I tried, latest code (it may be optimize) :

  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());

Upvotes: 4

Related Questions