Tuesday, November 11, 2014

Use velocity to generate XML requests

If you are interacting with third party services, there is a chance you will need to write up your request is XML format with details. I will show you how to use Velocity to generate your requests using an XML template.

Get the java library for Velocity Engine and add it to your class path.

Create a .vm file with a template


<MyRequest>
    <name>$name</name>
    <value>$double.doubleValue()</value>
    <action>$action</action>
</MyRequest>



Java Code

VelocityEngine engine = new VelocityEngine();
engine.init();

VelocityContext context = new VelocityContext();
context.put("name", "GET");
context.put("action", "someAction");
context.put("double", new Double(4));

Template template = engine.getTemplate(requestTemplateFile);

StringWriter writer = new StringWriter();
template.merge(context, writer);

System.out.println(writer.toString());

Your resulting xml will be like below


<MyRequest>
    <name>GET</name>
    <value>4.0</value>
    <action>someAction</action>
</MyRequest>

  

No comments: