1.pom.xml:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
2.具体实现:
(1)替换值
public static void main(String[] args) throws Exception {
String html = "D:/ceshi.html";
InputStream inputStream = new FileInputStream(html);// 读取html文件
int length = inputStream.available();
byte bytes[] = new byte[length];
inputStream.read(bytes);
inputStream.close();
String templateContent = new String(bytes,"UTF-8");
Map<String,Object> map = new HashMap<>();
//key值对应id
map.put("text1","text1");
map.put("text2","text2");
Document doc = Jsoup.parse(templateContent);
Elements select = doc.select("my-test");
for (Element e: select){
e.text((String) map.get(e.attr("id")));
}
doc.outerHtml();
log.info(doc.outerHtml());
}
(2)替换标签
public static void main(String[] args) throws Exception {
String source = "<p id=\"text1\">自定义标签第一种写法</p><p id=\"text2\">自定义标签第二种写法</p>";
Document doc = Jsoup.parse(source);
Elements select = doc.select("p#text1");
for (Element e: select){
e.tagName("a");
e.attr("href","http://www.baidu.com");
}
doc.outerHtml();
log.info(doc.outerHtml());
}