to my generated html after the body tag. I want it to end ...">

JSoup Add Wrapper div after body

I am trying to add <div class="wrapper">

to my generated html after the body tag. I want it to end </div>

before the end </body>

. So far i

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 get

 </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 html too. I only get it when using JSoup.

+3


source to share


1 answer


Jsoup Document normalizes text using the normalization method. The method is located here in the Document class. So it is wrapped in tags too.

In the Jsoup.parse () method, it can take three parameters: parse (String html, String baseUri, parser parser);

We'll give the parser parameter as Parser.xmlParser which uses XMLTreeBuilder (otherwise it uses HtmlTreeBuilder and normalizes html.).



I tried, the last code (can be optimized):

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

      

+4


source







All Articles