Velocity is a Java-based template engine (template engine). It allows anyone to simply use the template language (template language) to refer to objects defined by Java code.
Now let's take a look at this little example:
1. Create a velocity template to end with the VM, the template file in the example is TAXREPORTXML.VM, which reads as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
$name the parameters that you want the program to pass in.
2. The following is the code for Velocitytest:
Package velocity;
Import Java.io.File;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.text.MessageFormat;
Import Org.apache.velocity.Template;
Import Org.apache.velocity.VelocityContext;
Import Org.apache.velocity.app.VelocityEngine;
Import Org.joda.time.DateTime; public class Velocitytest {/** * @param args */public static void main (string[] args) {//Get velocityengine Ve
Locityengine ve = new Velocityengine ();
Get template file Template Template = ve.gettemplate ("/SRC/VELOCITY/TAXREPORTXML.VM", "UTF-8");
Velocitycontext context = new Velocitycontext ();
Incoming parameter Context.put ("name", "Jacky");
try {//generate XML FileWriter FileWriter = Getfilewriter ("Velocity_test.xml");
Invoke the merge method to pass into the context Template.merge (context, fileWriter);
Filewriter.flush ();
Filewriter.close ();
catch (IOException e) {e.printstacktrace (); }} private static FileWriter Getfilewriter (String FilenaMe) throws IOException {String FullPath = Messageformat.format ("{1}{0}{2}", File.separator,
"d://", fileName);
System.out.println ("fileName =" + FullPath);
File outputfile = new file (FullPath);
return new FileWriter (outputfile);
}
}
Look at the results of the operation, in D: velocity_test.xml:
<?xml version= "1.0" encoding= "Utf-8"?>
Parameters have been uploaded to XML, it's easy.