output XML by indent via transformer - Java XML

Java examples for XML:XSLT

Description

output XML by indent via transformer

Demo Code


//package com.java2s;
import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import javax.xml.transform.OutputKeys;
import org.w3c.dom.Node;

import java.io.Writer;

public class Main {
    public static void outputXML(Node e, Writer w) throws Exception {
        outputXML(e, w, 4);/*  w w w.  j a va 2s .co m*/
    }

    public static void outputXML(Node e, Writer w, int indent)
            throws Exception {
        // An identity transformer.
        TransformerFactory tf = TransformerFactory.newInstance();
        tf.setAttribute("indent-number", new Integer(indent));
        Transformer xformer = tf.newTransformer();

        DOMSource source = new DOMSource(e);
        StreamResult result = new StreamResult(w);
        xformer.setOutputProperty(OutputKeys.METHOD, "xml");
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.transform(source, result);
    }
}

Related Tutorials