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


Java Code

VelocityEngine engine = new VelocityEngine();

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


Your resulting xml will be like below



No comments: