3/20/2005

Working With XML In Java Using DOM

Filed under: — Aviran Mordo

XML technology is very popular with software development. One of the most common ways to work with XML files is using the ch is part of Java API for XML Processing. Although DOM gives you the basic functionality to work with XML files, simple operation it can be tedious if you don’t have several utility classes to work with DOM objects.
In this article we’ll write some useful utility methods that you should have in your arsenal when working with DOM objects.

The first method we’ll need in our arsenal is one to load an XML file and create a DOM object. In order to be as generic as we can we’ll use InputSource as our input.
Note in this method we’ll be using a default EntityResolver which is a good idea to have one. I’ll leave the implementation of getDTDResolver() and your own EntityResolver to you.


/**
* Creates and returns a Document from the given input source.
* @param inputSource the source of the document
* @param validating true if the parser should validate
* @param namespaceAware true if the parser should be namespaceAware
* @param errorHandler errorHandler for the DocumentBuilder
* @param coalescing true if the parser produced will convert CDATA
* nodes to Text nodes and append it to the adjacent (if any) text node; false otherwise.
* @param entityResolver the entity resolver
* @return the parsed and loaded DOM document.
* @exception XMLException if an error was encountered loading and parsing the file
*/
public static Document fromInputSource(InputSource inputSource, boolean validating, boolean namespaceAware, ErrorHandler errorHandler, boolean coalescing, EntityResolver entityResolver) throws XMLException
{
   DocumentBuilderFactory dbFact;
   Document doc;
   try
   {
     dbFact = DocumentBuilderFactory.newInstance();
     dbFact.setNamespaceAware(namespaceAware);
     dbFact.setValidating(validating);
     dbFact.setCoalescing(coalescing);
     DocumentBuilder db = dbFact.newDocumentBuilder();
     if (errorHandler != null)
     {
       db.setErrorHandler(errorHandler);
     }
     if (entityResolver != null)
     {
       db.setEntityResolver(new EntityResolverDelegate( new EntityResolver[] { entityResolver, getDTDResolver() }));
     }
     else
     {
       db.setEntityResolver(getDTDResolver());
     }
     doc = db.parse(inputSource);
   }
   catch (IOException e)
   {
     throw new XMLException("An error in parsing the input source", e);
   }
     catch (ParserConfigurationException e)
   {
     throw new XMLException("An error in parsing the input source", e);
   }
   catch (SAXException e)
   {
     throw new XMLException("An error in parsing the input source", e);
   }
   return doc;
}

Next it is a good idea to have some convenience methods to load your XML file such as fromInputSource, fromFile and fromString, in these methods just call the fromInputSource method we created.

Powered by WordPress