【发布时间】:2020-03-29 05:49:38
【问题描述】:
我有一个图像标签作为字符串。我需要解析标签并为标签添加类和高度和宽度。为此,我使用了以下 JSOUP 代码。
String imgTag = "<img class=\"fit-picture\" src=\"/Downloads/grapefruit-slice-332-332.jpg\" alt=\"Grapefruit slice atop a pile of other slices\">";
Document doc = Jsoup.parse(imgTag);
Elements img = doc.select("img");
for (Element image:img) {
image.addClass("abc");
String styleStr = image.attr("style");
boolean setSize = true;
if(styleStr != null && !styleStr.isEmpty() && (styleStr.contains("width") || styleStr.contains("height"))){
setSize = false;
}
if(setSize) {
String w = image.attr("width");
String h = image.attr("height");
if(w == null || w.isEmpty()) {
image.attr("width",width+"");
}
if(h == null || h.isEmpty() ) {
image.attr("height",height+"");
}
}
}
String imgrep = doc.body().html();
输出:
<img class="fit-picture abc" src="/Downloads/grapefruit-slice-332-332.jpg" alt="Grapefruit slice atop a pile of other slices" width="332" height="332">
在上面的代码中,是否可以在不创建 JSOUP 文档的情况下实现输出?就像独立的 Tag 或 Element 对象实现一样
提前致谢。
【问题讨论】: