How do I convert a Document object to a String in JAVA?



INTRODUCTION: We can use StringWriter for this purpose. StringWriter class is a character stream that collects it’s output into a StringBuffer, which can be used to construct a string.

 

StringWriter is a specialized Writer that writes characters to a StringBuffer, and then we can use method like toString() to get the string result.


Expected Output: This XML as a String

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

Source Code:

package com.interviewbubble.sample;import java.io.StringWriter;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;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 Document2String {    public static void main( String[] args ) throws ParserConfigurationException,                                                    TransformerConfigurationException,                                                    TransformerException    {        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();        DocumentBuilder dBuilder =dbFactory.newDocumentBuilder();        Document document = dBuilder.newDocument();        DOMSource domSource = new DOMSource(document);        StringWriter writer = new StringWriter();        StreamResult result = new StreamResult(writer);        TransformerFactory transformerFactory = TransformerFactory.newInstance();        Transformer transformer =transformerFactory.newTransformer();        transformer.transform(domSource, result);        String str = writer.toString();        System.out.println(  str );    }}

OUTPUT:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>