在写Demo时,需要将XML示例用语法高亮的格式显示在网页上,找了半天,没找到Java写的,java2html和JSyntaxHighlighter都只能转换Java代码,不能转XML,其它的大部分是JS写的,较出名的dp.SyntaxHighlighter生成的HTML代码不符合xhtml规范,还是自己先写个简单的用着,有好的工具请推荐下,谢谢。
public class XmlCodeFilter {
private String textColor = "#000000";
private String commentColor = "#3f5fbf";
private String tagColor = "#3f7f5f";
private String attributeColor = "#7f0055";
private String equalColor = "#000000";
private String stringColor = "#2a00ff";
private String entityColor = "#2a00ff";
private String dataColor = "#3f7f5f";
public String filter(String text) {
String result = text;
// 过滤CDATA //TODO 应该文本化CDATA里面的标签
result = result.replaceAll("<!\\[CDATA\\[([^(\\]\\])]*)\\]\\]>", "[datatempfont][lesstempsign]![CDATA[[/endtempfont]$1[datatempfont]]][greattempsign][/endtempfont]");
// 过滤注释
result = result.replaceAll("<!--([^(\\-\\->)]*)-->", "[commenttempfont][lesstempsign]!--$1--[greattempsign][/endtempfont]");
// 过滤标签
result = result.replaceAll("<([^(<|>)]+)>", "[tagtempfont][lesstempsign]$1[greattempsign]</font>");
// 过滤属性(双引号) //TODO 单双引号应改为反向引用方式
result = result.replaceAll("(\\s+)([\\w|:]+)(\\s*)\\=(\\s*)(\"[^\"]*\")", "$1[attributetempfont]$2</font>$3[equaltempfont]=</font>$4[stringtempfont]$5</font>");
// 过滤属性(单引号)
result = result.replaceAll("(\\s+)([\\w|:]+)(\\s*)\\=(\\s*)(\'[^\']*\')", "$1[attributetempfont]$2</font>$3[equaltempfont]=</font>$4[stringtempfont]$5</font>");
// 过滤&符号
//result = result.replaceAll("&", "&");
// 过滤dtd实体
result = result.replaceAll("(&[A-Z|a-z]+;)", "[entitytempfont]$1</font>");
// 过滤HtmlUnicode转码
result = result.replaceAll("(&#[0-9]+;)", "[entitytempfont]$1</font>");
// 过滤空格
result = result.replaceAll(" ", " ");
// 过滤缩进
result = result.replaceAll("\t", " ");
// 过滤Winodws换行
result = result.replaceAll("\r\n", "\n");
// 过滤换行
result = result.replaceAll("\n", "<br/>\n");
// 下面的替换把上面作的标记换成相应颜色
result = result.replaceAll("\\[lesstempsign\\]", "<");
result = result.replaceAll("\\[greattempsign\\]", ">");
result = result.replaceAll("\\[/endtempfont\\]", "</font>");
result = result.replaceAll("\\[commenttempfont\\]", "<font color=\"" + commentColor + "\">");
result = result.replaceAll("\\[datatempfont\\]", "<font color=\"" + dataColor + "\">");
result = result.replaceAll("\\[tagtempfont\\]", "<font color=\"" + tagColor + "\">");
result = result.replaceAll("\\[attributetempfont\\]", "<font color=\"" + attributeColor + "\">");
result = result.replaceAll("\\[equaltempfont\\]", "<font color=\"" + equalColor + "\">");
result = result.replaceAll("\\[stringtempfont\\]", "<font color=\"" + stringColor + "\">");
result = result.replaceAll("\\[entitytempfont\\]", "<font color=\"" + entityColor + "\">");
//return "<font color=\"" + textColor + "\">" + result + "</font>";
return result;
}
}