Velocity template escape XML from Velocity Context
<p>I have a velocity template, it represents an XML file. I am populating the text between tags using data passed to a VelocityContext object. This is then accessed inside the template.</p>

<p>Here is an example lets call it myTemplate.vm:</p>

<pre><code>&lt;text&gt;$myDocument.text&lt;/text&gt;
</code></pre>

<p>and this is how I am passing that data to the velocity file and building it to output as a String:</p>

<pre><code>private String buildXml(Document pIncomingXml)
  {
    // setup environment
    Properties lProperties = new Properties();
    lProperties.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

    VelocityContext lVelocityContext = new VelocityContext();
    lVelocityContext.put("myDocument" , pIncomingXml.getRootElement());

    StringWriter lOutput = new StringWriter();

    try
    {
      Velocity.init(lProperties);
      Velocity.mergeTemplate("myTemplate.vm", "ISO-8859-1", lVelocityContext, lOutput);
    }
    catch (Exception lEx)
    {
      throw new RuntimeException("Problems running velocity template, underlying error is " + lEx.getMessage(), lEx);
    }
    return lOutput.toString();
}
</code></pre>

<p>The problem is that when I access myDocument.text inside the template file it outputs text which is not escaped for XML.</p>

<p>I found a work around for this by also adding a VelocityContext for an escape tool like so:</p>

<pre><code>lVelocityContext.put("esc", new EscapeTool());
</code></pre>

<p>then wrapping my tag in the template using it:</p>

<pre><code>&lt;text&gt;$esc.xml($myDocument.text)&lt;/text&gt;
</code></pre>

<p>The reality is I have a very large template and for me to manually wrap each element in an $esc.xml context will be time consuming. Is there a way that I can tell velocity to escape for XML on access to myDocument without editing the template file at all?</p>