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"?> ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.