Java tutorial
//package com.java2s; /* * Copyright 2007 - 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.nio.charset.Charset; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.xml.sax.SAXException; public class Main { /** * Creates a {@link TransformerHandler}. * * @param commentHeader the comment header * @param rootTag the root tag * @param streamResult stream result */ public static TransformerHandler createTransformerHandler(String commentHeader, String rootTag, StreamResult streamResult, Charset charset) throws TransformerFactoryConfigurationError, TransformerConfigurationException, SAXException { SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); try { tf.setAttribute("indent-number", new Integer(2)); } catch (Exception e) { // ignore, workaround for JDK 1.5 bug, see http://forum.java.sun.com/thread.jspa?threadID=562510 } TransformerHandler transformerHandler = tf.newTransformerHandler(); Transformer serializer = transformerHandler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, charset.name()); serializer.setOutputProperty(OutputKeys.METHOD, "xml"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); transformerHandler.setResult(streamResult); transformerHandler.startDocument(); String newline = System.getProperty("line.separator"); if (newline == null) { newline = "\n"; } commentHeader = (newline + commentHeader).replaceAll("\\n--", newline + " "); transformerHandler.characters("\n".toCharArray(), 0, 1); transformerHandler.comment(commentHeader.toCharArray(), 0, commentHeader.toCharArray().length); transformerHandler.characters("\n".toCharArray(), 0, 1); if (rootTag.length() > 0) { transformerHandler.startElement("", "", rootTag, null); } return transformerHandler; } }