我有一个velocity模板,它代表一个XML文件。我正在使用传递给VelocityContext对象的数据填充标签之间的文本。然后可以在模板内访问这些数据。
下面是一个示例,我们称之为myTemplate.vm:
<text>$myDocument.text</text>
这是我如何将数据传递到Velocity文件中并构建为字符串输出的过程:
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();
}
问题在于当我在模板文件中访问myDocument.text时,输出的文本没有为XML转义。我已找到一种解决方法,即添加VelocityContext来使用转义工具:
lVelocityContext.put("esc", new EscapeTool());
然后在模板中使用它来包装我的标签:
<text>$esc.xml($myDocument.text)</text>
事实上,我有一个非常庞大的模板,手动将每个元素包装在$esc.xml上下文中对我来说将是耗时的。是否有一种方法可以告诉Velocity在访问myDocument时自动进行XML转义而不需要编辑模板文件呢?