3/20/2005

Working With XML In Java Using DOM

Filed under: Aviran Mordo @ 1:12 am

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.

 

Pages: 1 2 3 4 5

10 Responses to “Working With XML In Java Using DOM”

  1. Georgios Sam Says:

    Excellent work!!Really helpful.

  2. Anonymous Says:

    Thanks! Really useful .

  3. rajeez Says:

    Excellent work!!!!!
    write more article, u have a excelent way of persenting.
    i m work on xml in java.
    if u have some more info or detail . it will be helpfull.
    send it to rajeez@gmail.com

  4. JChuah Says:

    Thanks. This is really useful.

  5. Eduardo Says:

    Awesome! Code is pretty straightforward and thus easy to understand! Thanks Aviran!

  6. gps Says:

    Hi
    Would you have any idea how to save b;ank strings appearing in CDATA sections. I have observed that DOm removes the empty spaces.
    For eg.

    is rendered as

    is it possible to get the same format as after saving through DOM?

    TIA
    GPS

  7. gps Says:

    Hi
    Would you have any idea how to save blank strings appearing in CDATA sections. I have observed that DOM removes the empty spaces.
    For eg.
    “”

    is rendered as
    “”

    is it possible to get the same format as “” after saving through DOM?

    TIA
    GPS

  8. Urvashi Says:

    thanks a ton. Was looking around . Finally found some consolidated info. Though other sites did help too

  9. Borislav Kirilov Says:

    Yes, I used some of your methods! Very useful … for creating a new document I was using
    Document ontoFragment = builder.getDOMImplementation().createDocument(
    null, null, null);

    but your way looks like the correct one :)
    thanks for the effort!

  10. Sachin Says:

    HI Guys,

    Need Help:code for parsing XML String in JSP.

    example :

    data=”
    101
    Sachin

    Thank You

Leave a Reply

You must have Javascript enabled in order to submit comments.

All fields are optional (except comment).
Some comments may be held for moderation (depends on spam filter) and not show up immediately.
Links will automatically get rel="nofollow" attribute to deter spammers.

Powered by WordPress