Velocity模板从Velocity Context转义XML

Sui*_*ste 4 java xml velocity

我有一个速度模板,它代表一个XML文件.我使用传递给VelocityContext对象的数据填充标记之间的文本.然后在模板内访问它.

这是一个让我们称之为myTemplate.vm的例子:

<text>$myDocument.text</text>
Run Code Online (Sandbox Code Playgroud)

这就是我将数据传递给速度文件并将其构建为以字符串形式输出的方式:

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();
}
Run Code Online (Sandbox Code Playgroud)

问题是当我在模板文件中访问myDocument.text时,它输出的文本没有为XML转义.

我找到了一个解决方法,还为这样的转义工具添加了一个VelocityContext:

lVelocityContext.put("esc", new EscapeTool());
Run Code Online (Sandbox Code Playgroud)

然后使用它将我的标签包装在模板中:

<text>$esc.xml($myDocument.text)</text>
Run Code Online (Sandbox Code Playgroud)

实际情况是我有一个非常大的模板,对我来说,在$ esc.xml上下文中手动包装每个元素将非常耗时.有没有一种方法可以在不编辑模板文件的情况下告诉我在访问myDocument时转义XML的速度?

Cla*_*son 6

是的,这是可能的.

您需要做的是使用EscapeXMLReference,它实现了引用插入处理程序接口:

lProperties.put("eventhandler.referenceinsertion.class",
                 "org.apache.velocity.app.event.implement.EscapeXmlReference");
Run Code Online (Sandbox Code Playgroud)