Monthly Archives: February 2013

Creating HTML in Java with the DOM

Most of the HTML examples I’ve seen from Java date back to the stone ages, here’s an example of doing it the right way.

package demo;

import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

public class HTMLDemo {

   public static void main(String[] args) {
      FileOutputStream outputStream = null;

      try {
         Document newDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
         Element html = newDocument.createElement("html");
         Element head = newDocument.createElement("head");
         Element body = newDocument.createElement("body");

         Element p = newDocument.createElement("p");
         Text textNode = newDocument.createTextNode("Hello World");

         p.appendChild(textNode);
         body.appendChild(p);

         html.appendChild(head);
         html.appendChild(body);

         newDocument.appendChild(html);

         outputStream = new FileOutputStream("/demo.html");
         TransformerFactory.newInstance().newTransformer().transform(
               new DOMSource(newDocument), new StreamResult(outputStream));         

      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (outputStream != null) {
            try {
               outputStream.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
}