DOM Parser: How to write XML file in java

Connect with

Oracle Java
In this post, I tried to demonstrate how to write XML document in file or console using DOM parser. Writing a XML document using DOM (Document Object Model) parser in java is very easy.

1. Prerequisite for DOM parser

There is no any additional library need to put in your classpath or in project class path. Library (.jar) is already in added in J2SE.

2. Sample XML document

This is simple xml file which you need to write by using DOM parser in java.

File: ./docs/books.xml



  
	Ranjeet
	Pack Publishing
	1234-23423-234
   

3. DOM Parser to Write XML in file

package com.mysoftkey.jws.dom.ex1;

import java.io.File;

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.TransformerFactoryConfigurationError;
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;

/**
 * This java class is used to write xml document by using DOM parser
 * 
 * @author Ranjeet.Jha
 *
 */
public class WriteDOMxmlExample {

 public static final String filePathName = "./docs/books.xml";

 /**
  * @param args
  */
 public static void main(String[] args) {
  try {

    createBookDocument();
   //createBookXMLByDOM(); // using helper method.
  
  } catch (Exception tfe) {
   tfe.printStackTrace();
  }
 }
 
 /**
  * @throws ParserConfigurationException
  * @throws TransformerFactoryConfigurationError
  * @throws TransformerConfigurationException
  * @throws TransformerException
  */
 private static void createBookDocument() {
  try {

   DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

   // root elements
   Document doc = docBuilder.newDocument();
   
   Element rootElement = doc.createElement("book");
   doc.appendChild(rootElement);

   // employee elements
   Element employee = doc.createElement("book");
   rootElement.appendChild(employee);

   // set attribute to book element
   Attr attr = doc.createAttribute("id");
   attr.setValue("1");
   employee.setAttributeNode(attr);

   // isbn  elements
   Element isbnElement = doc.createElement("isbn");
   isbnElement.appendChild(doc.createTextNode("1234-23423-234"));
   employee.appendChild(isbnElement);
   
   // author elements
   Element authorElemnt = doc.createElement("author");
   authorElemnt.appendChild(doc.createTextNode("Ranjeet"));
   employee.appendChild(authorElemnt);

   // publisher elements
   Element publisherElement = doc.createElement("publisher");
   publisherElement.appendChild(doc.createTextNode("Pack Publishing"));
   employee.appendChild(publisherElement);

   // write the content into xml file
   TransformerFactory transformerFactory = TransformerFactory.newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   DOMSource source = new DOMSource(doc);
   StreamResult result = new StreamResult(new File(filePathName));

   // Output to console for testing
   //StreamResult result = new StreamResult(System.out);
   
   transformer.transform(source, result);

   System.out.println("File " + filePathName + " saved!");
  } catch (ParserConfigurationException pce) {
   pce.printStackTrace();
  } catch (TransformerException tfe) {
   tfe.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static Document getDocument() {

  DocumentBuilder docBuilder = null;
  Document doc = null;
  try {
   DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
   docBuilder = docFactory.newDocumentBuilder();

   // root elements
   doc = docBuilder.newDocument();
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  }

  return doc;
 }
 
}

Output:



  
	1234-23423-234
	Ranjeet
	Pack Publishing
   

4. By using Helper Utility method

Its always preferable to use helper method which can be reuse in multiple paces in project.

/**
  * This method used to write xml using another helper method.
  */
 private static void createBookXMLByDOM() {
  try{
  Document doc = getDocument();
  Element rootElement = doc.createElement("books");
  doc.appendChild(rootElement);

  // employee elements
  Element employee = doc.createElement("book");
  rootElement.appendChild(employee);
  employee.appendChild(addChildElement(doc, "isbn", "1234-23423-234"));
  employee.appendChild(addChildElement(doc, "author", "ranjeet"));
  employee.appendChild(addChildElement(doc, "publisher", "Packt Publishing"));
  employee.setAttributeNode(addAttribute(doc, "id", "1"));

  // create the xml file transform the DOM Object to an XML File
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();

  DOMSource domSource = new DOMSource(doc);
  StreamResult streamResult = new StreamResult(new File(filePathName));

  /*
   * If you use StreamResult result = new StreamResult(System.out); the output
   * will be pushed to the standard output and used for debugging purpose
   */
  // StreamResult result = new StreamResult(System.out);

  transformer.transform(domSource, streamResult);

  System.out.println("Done creating XML File");
  }catch(Exception e) {
   System.err.println("Error occured while writing xml. msg :" + e.getMessage());
  }
 }

/**
  * This method is used to add the child element.
  * 
  * @param document
  * @param nodeName
  * @param nodeValue
  * @return
  */
 public static Element addChildElement(Document document, String nodeName, String nodeValue) {
  Element element = document.createElement(nodeName);
  element.appendChild(document.createTextNode(nodeValue));
  // employee.appendChild(firstName);

  return element;
 }

 /**
  * This method is used to write a attribute in provided doc.
  * 
  * @param doc
  * @param name
  * @param value
  * @return
  */
 public static Attr addAttribute(Document doc, String name, String value) {
  Attr attr = doc.createAttribute(name);
  attr.setValue(value);
  return attr;
 }

Your comment is welcome to improve this post. Happy Learning 🙂


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *