Java tutorial
//package com.java2s; import java.io.Reader; import java.io.Writer; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.URIResolver; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.xml.sax.InputSource; public class Main { public static void formatXML(Document xml, Document xsl, URIResolver resolver, Writer output) throws Exception { try { DOMSource xslSource = new DOMSource(xsl); DOMSource xmlSource = new DOMSource(xml); Result result = new StreamResult(output); formatXML(xmlSource, xslSource, resolver, result); } finally { output.close(); } } public static void formatXML(Document xml, Document xsl, Writer output) throws Exception { formatXML(xml, xsl, null, output); } public static void formatXML(Reader xml, Reader xsl, URIResolver resolver, Writer output) throws Exception { try { try { try { Source xmlSource = new SAXSource(new InputSource(xml)); Source xslSource = new SAXSource(new InputSource(xsl)); Result result = new StreamResult(output); formatXML(xmlSource, xslSource, resolver, result); } finally { output.close(); } } finally { xsl.close(); } } finally { xml.close(); } } public static void formatXML(Reader xml, Reader xsl, Writer output) throws Exception { formatXML(xml, xsl, null, output); } /** * @param xmlSource * @param xslSource * @param resolver * @param output * @throws TransformerFactoryConfigurationError * @throws TransformerConfigurationException * @throws TransformerException */ public static void formatXML(Source xmlSource, Source xslSource, URIResolver resolver, Result result) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { TransformerFactory factory = TransformerFactory.newInstance(); Templates t = factory.newTemplates(xslSource); Transformer transformer = t.newTransformer(); if (resolver != null) { transformer.setURIResolver(resolver); } transformer.transform(xmlSource, result); } }