Java Basics Three: Using the velocity template to generate XML

Source: Internet
Author: User

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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.