Where can I find a simple Java example of creating an XML document and saving it to a file?

Davanum Srinivas

The following example is an extract from Intro to JDOM by Elliotte Rusty Harold.

import java.io.*;
import org.w3c.dom.*;
import org.apache.xerces.dom.*;
import org.apache.xml.serialize.*; 

public class HelloDOM {

  public static void main(String[] args) {
    try {
      DOMImplementationImpl impl = (DOMImplementationImpl) 
      DocumentType type = impl.createDocumentType("GREETING", null, null);
      // type is supposed to be able to be null, 
      // but in practice that didn't work                     
      DocumentImpl hello 
       = (DocumentImpl) impl.createDocument(null, "GREETING", type);
      Element root = hello.createElement("GREETING");
      // We can't use a raw string. Instead we have to first create 
      // a text node.
      Text text = hello.createTextNode("Hello DOM!");
      // Now that the document is created we need to *serialize* it
      try {
        OutputFormat format = new OutputFormat(hello);
        XMLSerializer serializer = new XMLSerializer(System.out, format);
      catch (IOException e) {
    catch (DOMException e) {