我有一个看起来像这样的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做到这一点?非常感谢你!
答案 0 :(得分:1)
如果要将全身包裹在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>