Last Updated: February 25, 2016
·
1.538K
· wlievens

Simple Java HTML syntax highlighter for XML code

This simple code snippet will generate better looking html for <pre> elements with XML snippets in them. It may be dirty, but it's simple and effective.

public final String highlight(String source)
{
    source = source.replaceAll("<([^>/]*)/>", "&lt;~blue~$1~/~/&gt;");
    source = source.replaceAll("<([^>]*)>", "&lt;~blue~$1~/~&gt;");
    source = source.replaceAll("([\\w]+)=\"([^\"]*)\"", "~red~$1~/~~black~=\"~/~~green~$2~/~~black~\"~/~");
    source = source.replaceAll("~([a-z]+)~", "<span style=\"color: $1;\">");
    source = source.replace("~/~", "</span>");
    return source;
}