javajsoupswiftsoup

Jsoup: wrap text belonging to body in a div?


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!


Solution

  • 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>