Java中使用htmlparser清除项目中的指定样式
因为项目规范问题,要统一清除指定的样式,所以学习了下htmlparser的使用。
htmlparser的基础教程有很多,这边就不多解释。
import com.google.common.io.Files;
import org.apache.commons.lang.StringUtils;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.CssSelectorNodeFilter;
import org.htmlparser.tags.Div;
import org.htmlparser.util.NodeList;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* Created by john on 2016/9/9.
*/
public class htmlTest {
public static String DEFAULT_CHARSET = "GBK";
public static void main(String[] args) {
File file = new File("C:\\Users\\john\\htmlparser");
removeHtmlStyle(file);
}
public static void removeHtmlStyle(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File _file : files) {
removeHtmlStyle(_file);
}
} else {
removeMarginBottomStyle(file);
}
}
public static void removeMarginBottomStyle(File file) {
String html = "";
try {
html = Files.toString(file, Charset.defaultCharset());
if (StringUtils.isBlank(html)) {
return;
}
/*
filters : 过滤出来的样式,这边使用CssSelectorNodeFilter可以直接使用jquery选择器的语法来选择dom节点
相关的NodeFilter实现类会在下面附上图片。
*/
NodeFilter[] filters = new NodeFilter[]{new CssSelectorNodeFilter("div[class='form-inline row']")};
NodeFilter filter = new AndFilter(filters);
Parser parser = Parser.createParser(html, DEFAULT_CHARSET);
NodeList nodes = parser.extractAllNodesThatMatch(filter);
if (nodes != null && nodes.size() != 0) {
for (int i = 0, length = nodes.size(); i < length; i++) {
/*
筛选出来的节点清除样式:
1、缓存原节点 temp
2、过滤包含待清除样式的节点
3、清除待清除样式的内容style
4、替换页面上缓存节点的内容成清楚后的节点
*/
Node node = nodes.elementAt(i);
String temp = node.toHtml(); //缓存原节点
Div div = (Div) node;
String style = div.getAttribute("style"); //找到自定义的style样式(style="margin-bottom: 10px;")
if (StringUtils.isNotBlank(style) && style.contains("margin-bottom")) { //待清除的样式
int start = style.indexOf(";", style.indexOf("margin-bottom")) + 1;
if (start == -1 || StringUtils.isBlank(style.substring(start, style.length()))) {
div.removeAttribute("style");
} else {
div.setAttribute("style", style.substring(start, style.length()));
}
html = StringUtils.replace(html, temp, div.toHtml()); //替换页面中的样式
}
}
}
Files.write(html, file, Charset.forName("utf8"));
File log = new File("C:\\Users\\john\\Desktop\\replace.log");
Files.append(file.getPath() + "\n", log, Charset.forName("utf8"));
} catch (IOException ioe) {
System.out.println("读取文件失败!" + ioe.getMessage());
} catch (Exception ex) {
System.out.println("发生异常:" + ex.getMessage());
}
System.out.println("====>" + file.getPath() + " [替换内容]");
}
}
Tag结构图:
NodeFilter结构图: