Java/Velocity/XML

Материал из Java эксперт
Перейти к: навигация, поиск

Show basic XML handling in a template

   <source lang="java">

/*

* Copyright 2000,2004 The Apache Software Foundation.
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.io.Writer; import org.apache.velocity.VelocityContext; import org.apache.velocity.Template; import org.apache.velocity.app.Velocity; import org.jdom.Document; import org.jdom.input.SAXBuilder;

/**

* Example to show basic XML handling in a template.
*
* @author 


Velocity Output XML

   <source lang="java">

import java.io.StringWriter; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; public class EmailDemo {

   public static void main( String[] args )
       throws Exception
   {
       /*
        *   first, get and initialize an engine
        */
       VelocityEngine ve = new VelocityEngine();
       ve.init();
       /*
        *   organize our data 
        */
       ArrayList list = new ArrayList();
       Map map = new HashMap();
       map.put("name", "Cow");
       map.put("price", "$100.00");
       list.add( map );

       map = new HashMap();
       map.put("name", "Eagle");
       map.put("price", "$59.99");
       list.add( map );
       map = new HashMap();
       map.put("name", "Shark");
       map.put("price", "$3.99");
       list.add( map );
       /*
        *  add that list to a VelocityContext
        */
       VelocityContext context = new VelocityContext();
       context.put("petList", list);
       /*
        *   get the Template  
        */
       Template t = ve.getTemplate( "./src/email_xml.vm" );
       /*
        *  now render the template into a Writer, here 
        *  a StringWriter 
        */
       StringWriter writer = new StringWriter();
       t.merge( context, writer );
       /*
        *  use the output in the body of your emails
        */
       System.out.println( writer.toString() );
   }

}


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

  1. foreach( $pet in $petList )
 <pet>
   <name>$pet.name</name>
   <price>$pet.price</price>
 </pet>
  1. end

</salelist>

      </source>