Java XML Document Format toFormattedString(Document element)

Here you can find the source of toFormattedString(Document element)

Description

Outputs a DOM Document node to a string with identation.

License

Open Source License

Parameter

Parameter Description
element a parameter

Declaration

public static String toFormattedString(Document element) 

Method Source Code

//package com.java2s;
/**/* w ww . jav  a2  s .co m*/
 * This file belongs to the BPELUnit utility and Eclipse plugin set. See enclosed
 * license file for more information.
 * 
 */

import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

import org.w3c.dom.Node;

public class Main {
    /**
     * Outputs a DOM Document node to a string with identation.
     * 
     * @param element
     * @return
     */
    public static String toFormattedString(Document element) {
        try {
            return serializeXML(element);
        } catch (TransformerException e) {
            return "(no data)";
        }
    }

    private static String serializeXML(Node node) throws TransformerException {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        ByteArrayOutputStream bOS = new ByteArrayOutputStream();
        t.transform(new DOMSource(node), new StreamResult(bOS));
        return bOS.toString();
    }
}

Related

  1. printDocument(Document document)
  2. printDocument(Document document)
  3. printDocument(Document document)
  4. printPrettyXML(Document doc)
  5. saveDocumentToFormattedStream(Document doc, OutputStream outputStream)