公司是前后端分离的架构,有个功能前端使用了富文本编辑器,通过该富文本编辑器得到的html文本与实际要求有一定差距,但是前端又处理不了,因此该处理只能由我们后端处理了。
第一想法是通过处理XML文档的方式处理前端传来html文本,由于前端传来的html文本并不是规范的XML,因此只能考虑其他方法。
后来发现Jsoup可以解析html文本,解决了问题。
class Test {
public static void main(String[] args) {
// 获取html文档。
Document document = Jsoup.parse("<img><img>");
// 拿到全部img标签,并设置src属性
Iterator<Element> imgs = document.select("img").iterator();
while (imgs.hasNext()) {
Element img = imgs.next();
img.attr("src", "http://xxx.com");
}
System.out.println(document);
}
}
输出结果
<html>
<head></head>
<body>
<img src="http://xxx.com" />
<img src="http://xxx.com" />
</body>
</html>