Create xml with dom parser

This example will show how to create xml document and create xml nodes with the DOM parser. The Document Object Model (DOM) java APIs allows you to create, modify, delete, and rearrange nodes. To create xml we will follow the high level process:

  • Create DocumentBuilder class
  • Create Element(s) and append to the document
  • Tranform classes into XML and send to an output source

The set up section creates a constant where we will validate the output produced using a junit test case. Two additional snippets will show how to output the xml to a file or to your console for local debugging.

Setup

String formattedXML ="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"+
    "<movie id=\"tt0111161\">\n"+
    "<rating>9.3</rating>\n"+
    "<title>The Shawshank Redemption</title>\n"+
    "<genre>Crime|Drama</genre>\n"+
    "</movie>\n"+
    "";

With DOM parser

@Test
public void create_xml() throws TransformerException, ParserConfigurationException {

  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document movieDocument = db.newDocument();

  org.w3c.dom.Element movieElement = movieDocument.createElement("movie");
  movieElement.setAttribute("id", "tt0111161");
  movieDocument.appendChild(movieElement);

  org.w3c.dom.Element ratingElement = movieDocument.createElement("rating");
  Text text1 = movieDocument.createTextNode("9.3");
  ratingElement.appendChild(text1);
  movieElement.appendChild(ratingElement);

  org.w3c.dom.Element titleElement = movieDocument.createElement("title");
  Text text2 = movieDocument.createTextNode("The Shawshank Redemption");
  titleElement.appendChild(text2);
  movieElement.appendChild(titleElement);

  org.w3c.dom.Element genreElement = movieDocument.createElement("genre");
  Text text3 = movieDocument.createTextNode("Crime|Drama");
  genreElement.appendChild(text3);
  movieElement.appendChild(genreElement);

  // Output the XML
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  Transformer transformer = transformerFactory.newTransformer();
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");

  DOMSource source = new DOMSource(movieDocument);
  StringWriter xmlWrittenToString = new StringWriter();
  StreamResult streamResult = new StreamResult(xmlWrittenToString);

  //transform xml source to result
  transformer.transform(source, streamResult);

  assertEquals(formattedXML, xmlWrittenToString.toString());
}

Logging output to console

StreamResult result =  new StreamResult(System.out);
transformer.transform(source, streamResult);

Logging output to file

StreamResult result =  new StreamResult(Paths.get("path").toFile());
transformer.transform(source, streamResult);