4

我有一个看起来像这样的 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 中,或者将整个正文(文本和其他 div)包装在顶级 div 中。有没有办法用 JSoup 做到这一点?非常感谢你!

4

1 回答 1

3

如果你想将整个身体包裹在一个 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>

于 2018-06-28T09:05:17.863 回答