5

I have an html string that looks something like this:

<body>
I am a text that needs to be wrapped in a div!
<div class=...>
  ...
</div>
...
I am more text that needs to be wrapped in a div!
...
</body>

So I need to wrap that dangling html text in its own div, or wrap the whole body (text and the other divs) in a top level div. Is there a way to do this with JSoup? Thank you very much!

Lucas P.
  • 4,282
  • 4
  • 29
  • 50

1 Answers1

4

If you want to wrap whole body in a div try this:

    Element body = doc.select("body").first();
    Element div = new Element("div");
    div.html(body.html());
    body.html(div.outerHtml());

Result:

<body>
  <div>
    I am a text that needs to be wrapped in a div! 
   <div class="...">
     ... 
   </div> ... I am more text that needs to be wrapped in a div! ... 
  </div>
 </body>

If you want to wrap each text in separate div try this:

    Element body = doc.select("body").first();
    Element newBody = new Element("body");

    for (Node n : body.childNodes()) {
        if (n instanceof Element && "div".equals(((Element) n).tagName())) {
            newBody.append(n.outerHtml());
        } else {
            Element div = new Element("div");
            div.html(n.outerHtml());
            newBody.append(div.outerHtml());
        }
    }
    body.replaceWith(newBody);

<body>
  <div>
    I am a text that needs to be wrapped in a div! 
  </div>
  <div class="...">
    ... 
  </div>
  <div>
    ... I am more text that needs to be wrapped in a div! ... 
  </div>
 </body>
Luk
  • 2,186
  • 2
  • 11
  • 32