Java XML Format format(Node node)

Here you can find the source of format(Node node)

Description

format

License

LGPL

Declaration

public static String format(Node node) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {
    public static String format(Node node) {
        try {/*from  w  w w . ja  va 2  s.c o m*/
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            StringWriter sw = new StringWriter();
            transformer.transform(new DOMSource(node), new StreamResult(sw));
            String actualFormatted = sw.toString();
            return actualFormatted;
        } catch (Exception e) {
            throw runtimeException(e);
        }
    }

    public static RuntimeException runtimeException(Exception e) {
        if (e instanceof RuntimeException)
            return (RuntimeException) e;
        else
            return new RuntimeException(e);
    }
}

Related

  1. applyTransformation(InputStream xsltStream, Map xsltParameters, InputStream inputXmlStream, OutputStream outputStream)
  2. format(final String xml)
  3. format(Node node, String indent)
  4. format(String unformattedXml)
  5. formatAttributes(Node node)
  6. formattedPrint(Node xml, OutputStream out)