我有一个图像标签作为字符串。我需要解析标签并添加标签的类以及高度和宽度。为此,我使用了以下 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 对象一样实现
提前致谢。
最佳答案
据我所知,你不能。您可以使用Jsoup.parseBodyFragment(imgTag)
反而。它还返回一个 Document
但一个空 shell,并确保解析的标签位于正文中。
您还可以像这样跳过文档创建:
final List<Node> nodes = Parser.parseFragment(imgTag, null, "");
但结果仍然是一个包含以下 HTML 的节点的列表:
<html>
<head></head>
<body>
<img class="fit-picture" src="/Downloads/grapefruit-slice-332-332.jpg" alt="Grapefruit slice atop a pile of other slices">
</body>
</html>
关于java - 如何在不创建JSOUP文档的情况下处理图像标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175798/