Luc*_* P. 5 java jsoup swiftsoup
我有一个 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>
Run Code Online (Sandbox Code Playgroud)
所以我需要将悬挂的 html 文本包装在它自己的 div 中,或者将整个正文(文本和其他 div)包装在顶级 div 中。有没有办法用 JSoup 来做到这一点?非常感谢!
如果你想将整个 body 包裹在 div 中,请尝试以下操作:
Element body = doc.select("body").first();
Element div = new Element("div");
div.html(body.html());
body.html(div.outerHtml());
Run Code Online (Sandbox Code Playgroud)
结果:
Element body = doc.select("body").first();
Element div = new Element("div");
div.html(body.html());
body.html(div.outerHtml());
Run Code Online (Sandbox Code Playgroud)
如果你想将每个文本包装在单独的 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);
Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1663 次 |
| 最近记录: |