java - 如何在不创建 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 对象实现一样
提前致谢。
解决方案
据我所知,你不能。你可以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>
推荐阅读
- sql - 这个 sql 注入尝试做什么以及如何检查它是否有效?
- javascript - Javascript 自然排序对象
- c# - NLog 4.1.2 在构造函数中崩溃
- linux - 根据用户输入将文本插入文件最后一行的 Shell 脚本
- java - 将静态方法传递给按钮工厂(Java)
- aspose - ASPOSE.WORDS.CLOUD 的文档类
- spring - 春季启动:FactoryBean
已初始化 jwt 令牌标头 - redis - 使用 Redisson 的多个独立应用程序可以共享同一个集群 Redis 吗?
- django - 基于 Django 类的视图从表单查询数据库并显示结果
- c# - 获取列表
取模结果等于 0 的整数,不使用循环