Java tutorial
//package com.java2s; /*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved. */ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.StringWriter; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Main { /** * Use the transform specified by xslSrc and transform the document specified by docSrc, and return the resulting * document. * * @param xslSrc * StreamSrc containing the xsl transform * @param docSrc * StreamSrc containing the document to be transformed * @param params * Map of properties to set on the transform * @param resolver * URIResolver instance to resolve URI's in the output document. * * @return StringBuffer containing the XML results of the transform * @throws TransformerConfigurationException * if the TransformerFactory fails to create a Transformer. * @throws TransformerException * if actual transform fails. */ protected static final StringBuffer transformXml(final StreamSource xslSrc, final StreamSource docSrc, final Map params, final URIResolver resolver) throws TransformerConfigurationException, TransformerException { StringBuffer sb = null; StringWriter writer = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); if (null != resolver) { tf.setURIResolver(resolver); } // TODO need to look into compiling the XSLs... Transformer t = tf.newTransformer(xslSrc); // can throw // TransformerConfigurationException // Start the transformation if (params != null) { Set<?> keys = params.keySet(); Iterator<?> it = keys.iterator(); String key, val; while (it.hasNext()) { key = (String) it.next(); val = (String) params.get(key); if (val != null) { t.setParameter(key, val); } } } t.transform(docSrc, new StreamResult(writer)); // can throw // TransformerException sb = writer.getBuffer(); return sb; } }