tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Template Engines > Freemarker > String XML and XHTML Escape

String XML and XHTML Escape 

FreeMarker is a java based template engine for complex template processing. This requires the library freemarker-2.3.16.jar to be in classpath. The following example shows escaping xml and xhtml using built-in functions.

File Name  :  
/FREEMARKER001/config/xml.ftl 

File Name  :  
com/bethecoder/tutorials/freemarker/tests/StringXMLTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.freemarker.tests;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class StringXMLTest {

  /**
   @param args
   @throws IOException 
   @throws TemplateException 
   */
  public static void main(String[] argsthrows IOException, TemplateException  {

    //Get template from classpath
    Configuration cfg = new Configuration();
    cfg.setClassForTemplateLoading(StringXMLTest.class, "/");
    Template template = cfg.getTemplate("xml.ftl");
    
    //Prepare data model
    Map<String, Object> dataModel = new HashMap<String, Object>();
    dataModel.put("msg"
        "<html><body>" 
        "'One', 'two', \"Three & Four\"" +
        "</body></html>");
    
    //Merge template and data
    OutputStreamWriter output = new OutputStreamWriter(System.out);
    template.process(dataModel, output);
  }
}
   

It gives the following output,
File Name  :  OUTPUT
   
<html><body>'One', 'two', "Three & Four"</body></html>

&lt;html&gt;&lt;body&gt;&apos;One&apos;, &apos;two&apos;, &quot;Three &amp; Four&quot;&lt;/body&gt;&lt;/html&gt;

&lt;html&gt;&lt;body&gt;&#39;One&#39;, &#39;two&#39;, &quot;Three &amp; Four&quot;&lt;/body&gt;&lt;/html&gt;
   



 
  


  
bl  br