Friday, May 21, 2010

Escaping HTML String using Groovy

As all of you know, I use SyntaxHighlighter for formatting the source code. If let's say you have HTML or XML source, you need to escape it first in order for SyntaxHighlighter to display it correctly.

I created a small utility for that purpose. Make sure you include Apache commons-lang in your classpath.

import org.apache.commons.lang.StringEscapeUtils

validateArgs(this.args)

new File(this.args[0]).eachLine {
    println StringEscapeUtils.escapeHtml(it)
}

def validateArgs(def args) {
    if (args.size() != 1) {
        printUsage()
        System.exit(1)
    }

    if (!new File(args[0]).isFile()) {
        printUsage()
        System.exit(1)
    }
}

def printUsage() {
    println "Usage: HtmlEscape.groovy <file>"
}

No comments:

Post a Comment