Java tutorial
//package com.java2s; /* This file is licensed to You 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.StandardCharsets; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; public class Main { /** ask to pretty-print XML (indentation) */ public static final String XSLT_INDENT_PROP = "{http://xml.apache.org/xslt}indent-amount"; /** set up transformer to output a standalone "fragment" - suppressing xml declaration * @param tf see {@link #transformerFactory()} * @return Transformer that is fully set up */ public static Transformer newFragmentTransformer(final TransformerFactory tf) throws TransformerConfigurationException { final Transformer transformer = tf.newTransformer(); setUtfEncoding(transformer); setIndentFlag(transformer); setTransformerIndent(transformer); outputStandaloneFragment(transformer); return transformer; } /** ask transformer to use UTF-8 * @param transformer will encode output as UTF-8 */ public static void setUtfEncoding(final Transformer transformer) { transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name()); } /** ask transformer to pretty-print the output * @param transformer will indent output */ public static void setIndentFlag(final Transformer transformer) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // see http://www.w3.org/TR/xslt#output } /** ask transformer to pretty-print the output: works with Java built-in XML engine * @param transformer will add indent property */ public static void setTransformerIndent(final Transformer transformer) { try { transformer.setOutputProperty(XSLT_INDENT_PROP, "4"); } catch (final IllegalArgumentException e) { System.err.println("indent-amount not supported: {}" + e.toString()); // ignore error, don't print stack-trace } } /** ask transformer to output stand-alone fragment * @param transformer will suppress xml declaration */ public static void outputStandaloneFragment(final Transformer transformer) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } }