3/20/2005

Working With XML In Java Using DOM

Filed under: — Aviran Mordo @ 1:12 am

Now all we have left is to save the Document to a file or write it to a String.
In order to output the Document to a more persistent format we’ll need to use the Transformer to help us with that.


/**
* Returns the document passed as a string.
* @param doc the Document to convert to string
* @param outputDocType set to true if you want to output the document type node
* @return the Document as a string
* @exception XMLException if an error occurred converting the document to a string
*/
public static String toString(Document doc, boolean outputDocType) throws XMLException
{
   StringWriter writer = new StringWriter();
   Transformer transformer;
   try
   {
     transformer = TransformerFactory.newInstance().newTransformer();
     if (outputDocType)
     {
       DocumentType type = doc.getDoctype();
       if (type != null)
       {
         String publicId = type.getPublicId();
         if (publicId != null)
         {
           transformer.setOutputProperty(DOCTYPE_PUBLIC, publicId);
         }
         String systemId = type.getSystemId();
         if (systemId != null)
         {
           transformer.setOutputProperty(DOCTYPE_SYSTEM, systemId);
         }
       }
     }
   }
   catch (TransformerConfigurationException e)
   {
     throw new XMLException("Could not create a transformer.", e);
   }
   try
   {
     transformer.transform(new DOMSource(doc), new StreamResult(writer));
   }
   catch (TransformerException e)
   {
     throw new XMLException("Could not transform document.", e);
   }
   return writer.toString();
}

We’ll use similar technic to save our Document to a file.


/**
* Writes the document passed to the file passed.
* @param fileName the name of the file to store the document to
* @param XMLdoc the source document to transform to the file
* @param XSLdoc the XSL style sheet to apply to XMLdoc
* @param outputDocType set to true if you want to output the document type node
* @exception XMLException if an error occurred writing the document to the file
*/
public static void toFile(String fileName, Document XMLdoc,Document XSLdoc, boolean outputDocType) throws XMLException
{
   Transformer transformer;
   try
   {
     transformer = TransformerFactory.newInstance().newTransformer(new DOMSource(XSLdoc));
     if (outputDocType)
     {
       DocumentType type = XMLdoc.getDoctype();
       if (type != null)
       {
         String publicId = type.getPublicId();
         if (publicId != null)
         {
           transformer.setOutputProperty(DOCTYPE_PUBLIC, publicId);
         }
         String systemId = type.getSystemId();
         if (systemId != null)
         {
           transformer.setOutputProperty(DOCTYPE_SYSTEM, systemId);
         }
       }
     }
   }
   catch (TransformerConfigurationException e)
   {
     throw new XMLException("Could not create a transformer.", e);
   }
   try
   {
     transformer.transform(new DOMSource(XMLdoc), new StreamResult(new File(fileName)));
   }
   catch (TransformerException e)
   {
     throw new XMLException("Could not transform document.", e);
   }
}

Now that you’re armed with some good utility methods working with XML files should be piece of cake.

The example I’ve brought here are limited, and it might useful to add some more methods to your utility class. If you find this tutorial helpful feel free to leave a note and maybe I’ll write another XML article where I’ll show you how to do XSL transformations and some XML schema validation with error tracking.

 

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