How to XML escaping with Apache Velocity?

后端 未结 1 1339
死守一世寂寞
死守一世寂寞 2021-01-18 03:05

I am generating XML using Apache Velocity. What is the best (most straight-forward) way to XML-escape the output?

(I saw there is an escape tool, but could not figur

相关标签:
1条回答
  • 2021-01-18 04:00

    Take a look at event handlers.

    eventhandler.referenceinsertion.class = org.apache.velocity.app.event.implement.EscapeXmlReference
    

    Escape tool is a production ready as well if you need to escape only selective references (final version of tools was released just recently but it was in beta stage before that for 2 years if not longer)

    $esc.xml($var)
    

    How to init velocity tools.

    Include velocity-tools.xml into your project and enable required tools:

    <tools> 
        <data type="number" key="TOOLS_VERSION" value="2.0"/>
        <data type="boolean" key="GENERIC_TOOLS_AVAILABLE" value="true"/>
        <toolbox scope="application">
            <tool class="org.apache.velocity.tools.generic.AlternatorTool"/>
            <tool class="org.apache.velocity.tools.generic.DisplayTool"/>
            <tool class="org.apache.velocity.tools.generic.MathTool"/>
            <tool class="org.apache.velocity.tools.generic.NumberTool"/>
            <tool class="org.apache.velocity.tools.generic.ComparisonDateTool"/>
            <tool class="org.apache.velocity.tools.generic.ClassTool"/>
            <tool class="org.apache.velocity.tools.generic.ConversionTool"/>
            <tool class="org.apache.velocity.tools.generic.EscapeTool"/>
            <tool class="org.apache.velocity.tools.generic.FieldTool"/>
            <tool class="org.apache.velocity.tools.generic.ListTool"/>
            <tool class="org.apache.velocity.tools.generic.ResourceTool"/>
            <tool class="org.apache.velocity.tools.generic.SortTool"/>
        </toolbox>
        <toolbox scope="request">
            <tool class="org.apache.velocity.tools.generic.LoopTool"/>
            <tool class="org.apache.velocity.tools.generic.ContextTool"/>
            <tool class="org.apache.velocity.tools.generic.LinkTool"/>
            <tool class="org.apache.velocity.tools.generic.RenderTool"/>
        </toolbox>
    </tools>
    

    Then velocity context creation procedure would look like:

    ToolManager velocityToolManager = new ToolManager();
    velocityToolManager.configure("velocity-tools.xml");
    VelocityContext context = new VelocityContext(velocityToolManager.createContext());
    
    0 讨论(0)
提交回复
热议问题