工作上的一个问题,要对html代码中的所有文本进行处理,但由于部分处理可能会影响到html关键词或符号,所以解决思路为利用jsoup将html代码解析为document对象,递归遍历doc对象的node节点,将文本节点取出处理,再将处理后的文本回填后,把document重新输出为html代码,处理后写入数据库
public static void main(String[] args) {
String html = "填空。<div>当<i>a</i>( )时,0.8÷<i>a</i><0.8;当<i>a</i>( )时,0.8÷<i>a</i>>0.8;当<i>a</i>( )时,0.8÷<i>a</i>=0.8。(<i>a</i>不等于0)</div>";
Document document = Jsoup.parse(html);
//由于doc对象为树,所以需要用方法将节点全部取出
List<Node> nodes = document.childNodes();
//将取出后的节点递归遍历
selectNodes(nodes);
//去除“body”标签
System.out.println(document.body().toString().replaceAll("(?:<body>|</body>)",""));
}
public static void selectNodes (List<Node> nodes){
if(nodes != null){
for (Node node : nodes) {
//node的文本类型为TextNode
if (node instanceof TextNode){
String string = node.toString();
//处理取出的文本
string = strReplace(string);
//将处理后的文本回填
node.attr("#text",string);
}
selectNodes(node.childNodes());
}
}else {
return;
}
}
jsoup直接操作html代码还是非常方便的,以后有机会或许可以多了解一下
Comments NOTHING