Show output as a xml file using Velocity

This Example shows you how to show output as a xml file in velocity.

Show output as a xml file using Velocity

Show output as a xml file using Velocity

     

This Example shows you how to show output as a xml file in velocity. The method used in this example are described below:-  
1:- Initialize velocity run time engine through method  init().
2:- Create object of VelocityContext Class.
3:- Create Template class object, Template  class object is used for controlling template methods and properties.

template.merge(context, writer): Merge method of the Template class is used here for merging  the VelocityContext class object to produce the output.

#foreach( $stu in $stuList ): This works same as the for loop of java but with some enhanced functionality.

Here in the code given below we will take some values in map object and then add this map object in list. With the help this list object we will create output for all the given values as a xml file.

 

 

XMLOutput.java

package velocity.XML;

import java.io.*;
import java.util.*;
import org.apache.velocity.*;
import org.apache.velocity.app.*;

public class XMLOutput {

  public static void main(String[] args)
  throws Exception {
  VelocityEngine ve = new VelocityEngine();
  ve.init();

  ArrayList list = new ArrayList();
  Map map = new HashMap();

  map.put("rno""1");
  map.put("name""komal");
  map.put("libno"1001);
  list.add(map);

  map = new HashMap();
  map.put("rno""2");
  map.put("name""santosh");
  map.put("libno"1002);
  list.add(map);

  map = new HashMap();
  map.put("rno""3");
  map.put("name""ajay");
  map.put("libno"1003);
  list.add(map);

  VelocityContext context = new VelocityContext();
  context.put("stuList", list);
  Template t = ve.getTemplate("./src/velocity/XMLOutput/xml.vm");
  StringWriter writer = new StringWriter();

  t.merge(context, writer);
  System.out.println(writer.toString());
  }
}

XML.vm

<?xml version="1.0"?>
<student>

#foreach( $stu in $stuList )
  <studentDetail>
  <rno>$stu.rno</rno>
  <name>$stu.name</name>
  </studentDetail>

#end

#foreach( $stu in $stuList )
  <libCardDetail>
  <rno>$stu.rno</rno>
  <libno>$stu.libno</libno>
  </libCardDetail>

#end
</studentlist>

Output :

<?xml version="1.0"?>
<student>

  <studentDetail>
  <rno>1</rno>
  <name>komal</name>
  </studentDetail>

  <studentDetail>
  <rno>2</rno>
  <name>santosh</name>
  </studentDetail>

  <studentDetail>
  <rno>3</rno>
  <name>ajay</name>
  </studentDetail>


  <libCardDetail>
  <rno>1</rno>
  <libno>1001</libno>
  </libCardDetail>

  <libCardDetail>
  <rno>2</rno>
  <libno>1002</libno>
  </libCardDetail>

  <libCardDetail>
  <rno>3</rno>
  <libno>1003</libno>
  </libCardDetail>
</studentlist>

Download code