Jsoup:将属于正文的文本包装在 div 中?

Jsoup: wrap text belonging to body in a div?

我有一个 html 字符串,看起来像这样:

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

所以我需要将悬挂的 html 文本包装在它自己的 div 中,或者将整个正文(文本和其他 divs)包装在顶层 div。有没有办法用 JSoup 做到这一点?非常感谢!

如果你想将整个 body 包裹在 div 中,试试这个:

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

结果:

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

如果您想将每个文本包装在单独的 div 中,试试这个:

    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>