Java XML to String – Write XML Object to File Example

Java examples to read XML file and print XML string to console or write XML to file.

1) Convert XML to String

To convert XML object i.e org.w3c.dom.Document into string, you need following classes:

1.1) Print XML to Console or Log File

private static void writeXmlDocumentToXmlFile(Document xmlDocument)
{
	TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tf.newTransformer();
        
        // Uncomment if you do not require XML declaration
        // 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 document to string 
        transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));

        String xmlString = writer.getBuffer().toString();	
        System.out.println(xmlString);						//Print to console or logs
    } 
    catch (TransformerException e) 
    {
        e.printStackTrace();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

1.2) Write XML to File

private static void writeXmlDocumentToXmlFile(Document xmlDocument, String fileName)
{
	TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tf.newTransformer();
        
        //Uncomment if you do not require XML declaration
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        
        //Write XML to file
        FileOutputStream outStream = new FileOutputStream(new File(fileName)); 

        transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream));
    } 
    catch (TransformerException e) 
    {
        e.printStackTrace();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

2) Read XML from File

Example to read XML from .xml file to Document object.

private static Document convertXMLFileToXMLDocument(String filePath) 
{
	//Parser that produces DOM object trees from XML content
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	
	//API to obtain DOM Document instance
	DocumentBuilder builder = null;
	try 
	{
		//Create DocumentBuilder with default configuration
		builder = factory.newDocumentBuilder();
		
		//Parse the content to Document object
		Document xmlDocument = builder.parse(new File(filePath));
		
		return xmlDocument;
	} 
	catch (Exception e) 
	{
		e.printStackTrace();
	}
	return null;
}

3) Complete Example

The complete code used to run the example.

package com.howtodoinjava.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 XmlToStringExample 
{
	public static void main(String[] args) 
	{
		final String xmlFilePath = "employees.xml";
		
		//Use method to convert XML string content to XML Document object
		Document xmlDocument = convertXMLFileToXMLDocument( xmlFilePath );
		
		//Write to file or print XML
		writeXmlDocumentToXmlFile(xmlDocument, "newEmployees.xml");
	}

	private static Document convertXMLFileToXMLDocument(String filePath) 
	{
		//Parser that produces DOM object trees from XML content
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		//API to obtain DOM Document instance
		DocumentBuilder builder = null;
		try 
		{
			//Create DocumentBuilder with default configuration
			builder = factory.newDocumentBuilder();
			
			//Parse the content to Document object
			Document xmlDocument = builder.parse(new File(filePath));
			
			return xmlDocument;
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		return null;
	}
	
	private static void writeXmlDocumentToXmlFile(Document xmlDocument, String fileName)
	{
		TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            
            // Uncomment if you do not require XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            
            //Print XML or Logs or Console
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(xmlDocument), new StreamResult(writer));
            String xmlString = writer.getBuffer().toString();	
            System.out.println(xmlString);			
            
            //Write XML to file
            FileOutputStream outStream = new FileOutputStream(new File(fileName)); 
            transformer.transform(new DOMSource(xmlDocument), new StreamResult(outStream));
        } 
        catch (TransformerException e) 
        {
            e.printStackTrace();
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
	}
}

Input file.

<employees>
	<employee id="101">
		 <name>Lokesh Gupta</name>
	    <title>Author</title>
	</employee>
	<employee id="102">
		 <name>Brian Lara</name>
	    <title>Cricketer</title>
	</employee>
</employees>

Output file.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<employees>
	<employee id="101">
		 <name>Lokesh Gupta</name>
	    <title>Author</title>
	</employee>
	<employee id="102">
		 <name>Brian Lara</name>
	    <title>Cricketer</title>
	</employee>
</employees>

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “Java XML to String – Write XML Object to File Example”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.