Jsoup实现html值或者自定义标签替换

1.pom.xml:


    org.jsoup
    jsoup
    1.11.3

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 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 = "

自定义标签第一种写法

自定义标签第二种写法

"; 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()); }

 

你可能感兴趣的:(Jsoup实现html值或者自定义标签替换)