【问题标题】:Velocity template escape XML from Velocity ContextVelocity 模板从 Velocity 上下文中转义 XML
【发布时间】:2017-01-24 22:22:55
【问题描述】:

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

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

<text>$myDocument.text</text>

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

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 上下文中会很耗时。有没有一种方法可以告诉速度在访问 myDocument 时为 XML 转义,而无需编辑模板文件?

【问题讨论】:

  • 显然你问了两个不同的问题(并且可能混淆了关于它们的需求)。第一个问题是“是否可以在完全不编辑模板文件的情况下告诉速度在访问 myDocument 时为 XML 转义?”。第二个问题不是直接问的,但你觉得这里有些麻烦。这是“EscapeTool.xml() 对我来说太慢了。如何提高 xml 转义速度?”。关于第一个问题,我的猜测是“不”。您可以尝试使用 smthng 之类的:commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/… 吗?
  • 嗯,看起来这个 StringEscapeUtils 正是 EscapeTool.xml() 中使用的内容:grepcode.com/file/repository.springsource.com/…。那么您唯一可以改进的就是检查传入 Document 的 toString() 方法中发生了什么。你能测量pIncomingXml.toString()的时间吗?
  • 速度不是问题。它只是一个一个地转义每个元素的手动工作及其潜在的错误。

标签: java xml velocity


【解决方案1】:

是的,这是可能的。

你需要做的是使用EscapeXMLReference,它实现了reference insertion handler接口:

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

【讨论】:

  • 梦幻般的外观已经完全逃脱了我所需要的,而无需触摸模板文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 2011-09-28
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
  • 2018-05-29
  • 2019-07-29
相关资源
最近更新 更多