« Swami, this is a really dumb idea | Main | No sound in ImageMixer -- Google comes to rescue »

XInclude Processing with J2SE5.0

While working with long XML documents, I always felt it was better to break them into smaller documents and have a master document that could simply include the smaller documents. In fact, I always found it amazing that the base XML specification didn't include such a capability. This changed with XML Inclusion spec. becoming a W3C Proposed Recommendation.

Recently, while looking for a processor that allowed me to create a single XML document, starting with a document that included others, I was pleasantly surprized to find XML Inclusion support in J2SE5.0. You could simply mark a SAXParserFactory or DocumentBuilderFactory to be XIncludeAware and it will do the processing. To test this feature, I wrote this simple Java program that treads a XMl document with XInclude tags from standard input and writes the consolidated XML document to the standard output.

// --------------------------------------------------------
// File: XMLProcessor.java
// Description: An XML Processor to do XInclude Processing
// Author: Pankaj Kumar
// Copyright 2004 Pankaj Kumar. All Rights Reserved.
// License: This software is available under GPL.
// ---------------------------------------------------------
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.sax.SAXSource;
public class XMLProcessor {
public static void main(String[] args) throws Exception{
InputSource is = new InputSource(System.in);
SAXParserFactory spf = SAXParserFactory.newInstance();
XMLReader xr = spf.newSAXParser().getXMLReader();
SAXSource source = new SAXSource(xr, is);
StreamResult result = new StreamResult(System.out);
Transformer xf = TransformerFactory.newInstance().newTransformer();
xf.setOutputProperty(OutputKeys.INDENT, "yes");
xf.setOutputProperty(OutputKeys.METHOD, "xml");
xf.transform(source, result);

As You can see, I have used an identity transformation from SAXSource to StreamResult for serializing the XML document. This technique has the additional advantage of applying any XSLT transformation specified in the source document, justifying the XMLProcessor name of the program.

Comments (1)


This page contains a single entry from the blog posted on December 18, 2004 10:26 PM.

The previous post in this blog was Swami, this is a really dumb idea.

The next post in this blog is No sound in ImageMixer -- Google comes to rescue.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33