首页 > 解决方案 > 如何在不创建 JSOUP 文档的情况下处理图像标签

问题描述

我有一个图像标签作为字符串。我需要解析标签并为标签添加类和高度和宽度。为此,我使用了以下 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 对象实现一样

提前致谢。

标签: javahtmljsoup

解决方案


据我所知,你不能。你可以Jsoup.parseBodyFragment(imgTag)改用。它还返回一个Document空壳,并确保已解析的标签在正文中。

您也可以像这样跳过文档创建:

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>

推荐阅读