How to Convert a Document DOM Object to XML String Object

Explanation:

Document is an interface in org.w3c.dom package which extends Node Interface. This example is all about converting a document object to String Object which will be a valid XML. The method getXMLFromDOM() will take Document object as argument. So, we have created a document object using the method createDocument().
This createDocument() method is inturn clearly explained in my post How to Create or generate a Document Object.
In my another post, you can find a sample program to Convert a XML String to DOM / Document object.

In the current example in the method getXMLFromDOM(),
DOMSource acts as a holder for a transformation Source tree in the form of a Document Object Model (DOM) tree. It implements the Source interface.
StreamResult acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup. It is a class in javax.xml.transform.stream package which implements Result interface.
Transformer is an abstract class which can be instantiated with transformerFactory.newTransformer(). It is a class in javax.xml.transform package whose instance method transform() will transform the xml Dom source to Stream result. The getWriter() method of StreamResult will return a characterStream of return type Writer which will be converted to String Object using the toString() method.

 

 Java example to Convert a DOM / Document Object to XML String

package com.developprojects.java;

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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DocumentToString {

private static TransformerFactory transformerFactory = null;

public static void main(String[] args) {

transformerFactory = TransformerFactory.newInstance();
 String XML = new String();
 Document sampleDoc = createDocument();
 try {
 XML = getXMLFromDOM(sampleDoc);
 } catch (IllegalArgumentException e) {
 e.printStackTrace();
 } catch (TransformerConfigurationException e) {
 e.printStackTrace();
 } catch (TransformerException e) {
 e.printStackTrace();
 }
 System.out.println("String Generated from Document is " + XML);
 }

// This method will convert a Document to String Object
 public static String getXMLFromDOM(Document requestXMLDoc)
 throws IllegalArgumentException, TransformerConfigurationException,
 TransformerException {

if (requestXMLDoc == null) {
 System.out.println("Supplied document object is null");
 throw new IllegalArgumentException("Document cannot be null");
 }
 DOMSource source = new DOMSource(requestXMLDoc);
 StreamResult result = new StreamResult(new StringWriter());
 Transformer transformer;
 try {
 transformer = transformerFactory.newTransformer();
 transformer.transform(source, result);
 } catch (TransformerConfigurationException tConfigurationException) {
 System.out.println("TransformerConfigurationException::"
 + tConfigurationException);
 } catch (TransformerException transformerException) {
 System.out.println("TransformerConfigurationException::"
 + transformerException);
 }
 String returnString = result.getWriter().toString();

return returnString;
 }

// This method will create a Document Object
 public static Document createDocument() {
 DocumentBuilderFactory docFactory = DocumentBuilderFactory
 .newInstance();
 Document doc = null;
 try {
 DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 doc = docBuilder.newDocument();
 } catch (ParserConfigurationException e1) {
 e1.printStackTrace();
 }

Element rootElement = doc.createElement("SampleDoc");
 doc.appendChild(rootElement);
 Attr attr = doc.createAttribute("attr");
 attr.setValue("true");
 rootElement.setAttributeNode(attr);
 return doc;

}

}

How to Convert a XML String to Document Object

Explanation:

Document is an interface in org.w3c.dom package. It extents Node interface.  The domFactory.setNameSpaceAware()  method will have argument “true” as our parser produced will support XML namespace. In this example, we will give getDocFromXMLString() Method a String Argument. Please Note that this String Argument must be a  valid XML. The newDocumentBuilder will create new instance of DocumentBuilder with configured parameters. Then this String Argument will be Converted to Byte Array Input Stream.Then the builder.parse() method will take the Input Stream Argument to generate a Document Object. It is a good practice to close the streams in finally block.

You can find my other example to convert Dom / Document object to XML String here.

 Java example to Convert a XML String to DOM / Document Object
package com.developprojects.java;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class StringToDocument {

	private static DocumentBuilderFactory domFactory = null;
	private static final String XMLString = "<DevelopProjects>
                                                    <SampleXML>
                                                     This is just a Sample XML String
                                                     </SampleXML>
                                                  </DevelopProjects>";

	public static void main(String args[]) {
		domFactory = DocumentBuilderFactory.newInstance();
		domFactory.setNamespaceAware(true);
		try {
			Document doc = getDocFromXMLString(XMLString);
			System.out.println("Document is " + doc.getFirstChild());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Method to Convert a XML String to a Document Object.

	public static Document getDocFromXMLString(String xml) throws Exception {

		DocumentBuilder builder;
		Document doc;
		ByteArrayInputStream bis = null;
		try {
			builder = domFactory.newDocumentBuilder();
			bis = new ByteArrayInputStream(xml.getBytes());
			doc = builder.parse(bis);
		} catch (Exception exception) {
			System.out.println("Exception while generatign doc from xml string "
							+ exception);
			throw exception;
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
			} catch (IOException exception) {
				System.out.println("Exception while generatign doc from xml string "
								+ exception);
				throw exception;
			}
		}
		return doc;
	}
}

References:

Document Object Model

Document Interface

XML

DocumentBuilderFactory

DocumentBuilder