The following example performs a transformation using DOM nodes as input for the TransformerFactory, as input for the
Transformer, and as the output of the transformation.
TransformerFactory tfactory = TransformerFactory.newInstance();
// Make sure the TransformerFactory supports the DOM feature.
if (tfactory.getFeature(DOMSource.FEATURE) && tfactory.getFeature(DOMResult.FEATURE))
{
// Use javax.xml.parsers to create our DOMs.
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true); // do this always for XSLT
DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
// Create the Templates from a DOM.
Node xslDOM = docBuilder.parse(xslID);
DOMSource dsource = new DOMSource(xslDOM, xslID);
Templates templates = tfactory.newTemplates(dsource);
// Create the source tree in the form of a DOM.
Node sourceNode = docBuilder.parse(sourceID);
// Create a DOMResult that the transformation will fill in.
DOMResult dresult = new DOMResult();
// And transform from the source DOM tree to a result DOM tree.
Transformer transformer = templates.newTransformer();
transformer.transform(new DOMSource(sourceNode, sourceID), dresult);
// The root of the result tree may now be obtained from
// the DOMResult object.
Node out = dresult.getNode();
// Serialize it to System.out for diagnostics.
Transformer serializer = tfactory.newTransformer();
serializer.transform(new DOMSource(out), new StreamResult(System.out));
}