由于业务需要,有时会需要读取一个html模板。
有这么一个需求:需要读取html文件的“body”内容,但是不想要这个body里面的某一个<h2> 元素,如果用正则表达式来进行匹配的话,会非常消耗性能。可以考虑使用这个方法
<!doctype html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<title>helloWorld--zxk</title>
<meta name='description' content=''>
</head>
<body>
<h2 class="rich_media_title" id="activity-name">
<!-- 设置标题 -->
#titleName#
</h2>
<div>
</div>
<h2>1111</h2>
</body>
</html>
下面是Java代码
public static String readTxtFileBodyDoc(String filePath) {
StringBuilder sb = new StringBuilder();
try {
String encoding = "UTF-8";
//读取本地的html文件方法
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
// 进行body元素提取
Document document = null;
document = Jsoup.parse(file, encoding);
Element e = document.body();
Element e1 = e.getElementById("activity-name");
//排除 某一个<h2>元素
e1.remove();
String eStr = String.valueOf(e);
sb.append(eStr);
}
if (StringUtils.isEmpty(sb)) {
//读取线上的html文件地址
try {
Document doc = Jsoup.connect(filePath).get();
Element e = doc.body();
Element e1 = e.getElementById("activity-name");
e1.remove();
String eStr = String.valueOf(e);
sb.append(eStr);
} catch (Exception e) {
}
}
} catch (Exception e) {
e.printStackTrace();
}
String bodyCont = sb.toString();
return bodyCont;
}