O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.12. Accessing XML Documents from a Templating Engine

Problem

You need to reference XML nodes from a template.

Solution

Use FreeMarker and parse an XML document with the NodeModel class. A NodeModel is an object that allows access to an XML document as a hierarchy of named elements and attributes from a FreeMarker template. NodeModel has a public static method parse( ), which parses an XML document and returns a NodeModel to be added to your context Map. The following code parses an XML document and passes a NodeModel to a template:

import freemarker.template.Configuration;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import freemarker.ext.dom.NodeModel;

// Create a File Object for our XML data
File composers = new File("composers.xml");
NodeModel nodeModel = NodeModel.parse( composers );

Map root = new HashMap( );
root.put("doc", nodeModel); 

// A template is processed with a Map and output is sent to a Writer.
Template template = cfg.getTemplate("composerTable.ftl");
template.process(root, writer);
System.out.println("output: \n" + writer.toString( ));

A File object refers to an XML document, and NodeModel.parse( ) is used to parse this document to a NodeModel object, which is then placed in the root Map—the context with which the FreeMarker template will be merged. The XML document contains information about the lives of great classical composers, and the structure of this document is shown here:

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required