July 20, 2011

Creating a new XML document with DOM Parser and persisting the DOM Tree

The following code example demonstrates the power of the DOM Parser by creating an XML document on-the-fly with the create methods from the DOM Parser API - something that is not possible to do with a SAX Parser. The code also shows how to take a DOM Tree and convert it to a String (XML content). This String can then be persisted to an XML document file.

package info.icontraining.parsers;

import java.io.StringWriter;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.*;

public class DOMParserNewDocument implements ErrorHandler {
   public static void main(String[] args) throws TransformerException {

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      try {
         factory.setNamespaceAware(true);
         factory.setValidating(true);

         DocumentBuilder dom = factory.newDocumentBuilder();            
         dom.setErrorHandler(new DOMParserNewDocument());
         Document doc = dom.newDocument();

         Element invoiceElement = doc.createElement("Invoice");
         Attr invoiceNumberAttr = doc.createAttribute("invoice-number");
         invoiceNumberAttr.setNodeValue("123456");
         invoiceElement.setAttributeNode(invoiceNumberAttr);
         doc.appendChild(invoiceElement);

         Element dateElement = doc.createElement("date");         
         Element monthElement = doc.createElement("month");         
         Element dayElement = doc.createElement("day");
         Element yearElement = doc.createElement("year");

         monthElement.appendChild(doc.createTextNode("July"));
         dayElement.appendChild(doc.createTextNode("22"));
         yearElement.appendChild(doc.createTextNode("2011"));

         dateElement.appendChild(monthElement);          
         dateElement.appendChild(dayElement);
         dateElement.appendChild(yearElement);

         invoiceElement.appendChild(dateElement);  
         // convert DOM tree to XML string
   
         Transformer transformer =
                        TransformerFactory.newInstance().newTransformer();
         transformer.setOutputProperty(OutputKeys.INDENT, "yes");

         StreamResult result = new StreamResult(new StringWriter());
         DOMSource source = new DOMSource(doc);
         transformer.transform(source, result);

         String xmlString = result.getWriter().toString();
         System.out.println(xmlString);
     
      } catch (ParserConfigurationException e) {
         e.printStackTrace();
      } 
   }
 
   public void fatalError(SAXParseException err)
        throws SAXException {
      System.out.println("** Fatal Error"
                          + ", line " + err.getLineNumber()
                          + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());
   }

   public void error(SAXParseException err)        
         throws SAXParseException {
      System.out.println("** Error"
                          + ", line " + err.getLineNumber()
                          + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());
   }

   public void warning(SAXParseException err)         
        throws SAXParseException {
      System.out.println("** Warning"
                          + ", line " + err.getLineNumber()
                          + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());
   }
}

No comments:

Post a Comment