增加html格式化方法

This commit is contained in:
wanggeng 2022-04-13 16:27:27 +08:00
parent 7313fd52f2
commit 2963028aa7

View File

@ -1,5 +1,8 @@
package ink.wgink.util; package ink.wgink.util;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -56,4 +59,48 @@ public class HtmlHelper {
return html; return html;
} }
/**
* 格式化HTML代码
*
* @param code html代码
* @param indentType 缩进类型默认是空格
* @param indentCount 缩进数量
* @return
*/
public static String formatHtml(String code, String indentType, int indentCount) {
if (StringUtils.isBlank(code)) {
return null;
}
code = code.replaceAll(">\\s+<", "><");
String html = Jsoup.parseBodyFragment(code).body().html();
if (StringUtils.isBlank(html)) {
return null;
}
if (indentType == null) {
indentType = " ";
}
if (indentCount < 0) {
indentCount = 0;
}
String[] htmlArray = html.split("\n");
String result = "";
for (String htmlLine : htmlArray) {
int startIndex = htmlLine.indexOf("<");
String tab = "";
for (int i = 0; i < startIndex + indentCount; i++) {
tab += indentType;
}
htmlLine = tab + htmlLine.trim();
System.out.println(htmlLine);
result += htmlLine + "\n";
}
return result;
}
public static void main(String[] args) {
String code = "<div id=\"input_1\" class=\"layui-form-item \" data-id=\"input_1\" data-tag=\"input\" data-index=\"0\"> <label class=\"layui-form-label layui-form-required\" style=\"width: 110px;\"><span style=\"color:red;\">*</span>单行文本:</label> <div class=\"layui-input-block\" style=\"margin-left: 110px\"> <input name=\"input_1\" value=\"\" placeholder=\"请输入\" class=\"layui-input\" lay-vertype=\"tips\" lay-verify=\"required\" style=\"width:100%\"> </div></div>";
String result = formatHtml(code, "\t", 0);
System.out.println(result);
}
} }