Java XML Document Print printXML(Document doc)

Here you can find the source of printXML(Document doc)

Description

print XML

License

Open Source License

Parameter

Parameter Description
doc a parameter

Exception

Parameter Description
TransformerException an exception

Declaration

public static void printXML(Document doc) throws TransformerException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.StringWriter;

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;

public class Main {
    /**//from w  w  w.  j av a 2  s. c o  m
     * 
     * @param doc
     * @throws TransformerException
     */
    public static void printXML(Document doc) throws TransformerException {

        // A TransformerFactory instance can be used to create Transformer and
        // Templates objects.
        TransformerFactory tf = TransformerFactory.newInstance();

        // An instance of transformer can be obtained with the
        // TransformerFactory.newTransformer method. This instance may then be
        // used to process XML from a variety of sources and write the
        // transformation output to a variety of sinks.
        Transformer transformer = tf.newTransformer();

        // Set an output property that will be in effect for the transformation.
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        // A character stream that collects its output in a string buffer, which
        // can then be used to construct a string.
        StringWriter writer = new StringWriter();

        // Transform the XML Source to a Result. Specific transformation
        // behavior is determined by the settings of the TransformerFactory in
        // effect when the Transformer was instantiated and any modifications
        // made to the Transformer instance.
        transformer.transform(new DOMSource(doc), new StreamResult(writer));

        // Return the string buffer itself.
        String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

        // print output
        // System.out.println(output);

    }
}

Related

  1. printDocumentTree(Node el)
  2. printDOM(File file, Document doc, String encoding)
  3. printElements(Document doc)
  4. printElements(Document dom)
  5. printPI(Document doc, PrintStream pstrm)
  6. printXml(Document xml, Writer out)
  7. printXmlDocument(Document doc)
  8. printXMLDocument(Document document)
  9. printXMLFormat(Document document)