简体   繁体   English

Velocity模板从Velocity Context转义XML

[英]Velocity template escape XML from Velocity Context

I have a velocity template, it represents an XML file. 我有一个速度模板,它代表一个XML文件。 I am populating the text between tags using data passed to a VelocityContext object. 我使用传递给VelocityContext对象的数据填充标记之间的文本。 This is then accessed inside the template. 然后在模板内访问它。

Here is an example lets call it myTemplate.vm: 这是一个让我们称之为myTemplate.vm的例子:

<text>$myDocument.text</text>

and this is how I am passing that data to the velocity file and building it to output as a String: 这就是我将数据传递给速度文件并将其构建为以字符串形式输出的方式:

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();
}

The problem is that when I access myDocument.text inside the template file it outputs text which is not escaped for XML. 问题是当我在模板文件中访问myDocument.text时,它输出的文本没有为XML转义。

I found a work around for this by also adding a VelocityContext for an escape tool like so: 我找到了一个解决方法,还为这样的转义工具添加了一个VelocityContext:

lVelocityContext.put("esc", new EscapeTool());

then wrapping my tag in the template using it: 然后使用它将我的标签包装在模板中:

<text>$esc.xml($myDocument.text)</text>

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. 实际情况是我有一个非常大的模板,对我来说,在$ esc.xml上下文中手动包装每个元素将非常耗时。 Is there a way that I can tell velocity to escape for XML on access to myDocument without editing the template file at all? 有没有一种方法可以在不编辑模板文件的情况下告诉我在访问myDocument时转义XML的速度?

Yes, it's possible. 是的,这是可能的。

What you need to do is to use the EscapeXMLReference , which implements the reference insertion handler interface: 您需要做的是使用EscapeXMLReference ,它实现了引用插入处理程序接口:

lProperties.put("eventhandler.referenceinsertion.class",
                 "org.apache.velocity.app.event.implement.EscapeXmlReference");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM