3/20/2005

Working With XML In Java Using DOM

Filed under: Aviran Mordo @ 1:12 am

Not always you have an XML file to load, so we need a method to create new instance of a Document object. In order to do that we’ll use DocumentBuilder to create a new instance.

/**
* Creates a new XML document and returns it.
* @return a new XML document without any data
* @exception XMLException if an error occurred creating the new XML document
*/
public static Document newDocument() throws XMLException
{
   try
   {
     DocumentBuilderFactory factory;
     DocumentBuilder builder;
     factory = DocumentBuilderFactory.newInstance();
     factory.setNamespaceAware(false);
     factory.setValidating(false);
     builder = factory.newDocumentBuilder();
     return builder.newDocument();
   }
   catch (ParserConfigurationException e)
   {
     throw new XMLException("Error creating new document.", e);
   }
}

Now that we have the Document we’ll write some methods to manipulate the Document Nodes. The method names are pretty much self explanatory.


/**
* Creates a child element with a text value
* @param parent The parent element
* @param name The child's name (tag)
* @param textValue The text that goes in the child's element
* @return The newly created element
* @throws XMLException
*/
public static Element createChildElementWithText(Element parent, String name, String textValue)
throws XMLException
{
   Element child = parent.getOwnerDocument().createElement(name);
   parent.appendChild(child);
   setTextForNode(child, textValue);
   return child;
}

setTextForNode will be used to set a text for a node. In this method we’ll check first if the node we want to update already contains text. If it is then we’ll update the text value with the new value. If no text node exists then we’ll create a new text node as a child node of the current node.


/**
* Updates the text for the given node.
* @param node the node to update
* @param newValue the value to be place at that node
* @exception XMLException if an error occurred updating the XML Node
*/
public static void setTextForNode(Node node, String newValue) throws XMLException
{
   NodeList children;
   Node childNode;
   children = node.getChildNodes();
   boolean success = false;
   if (children != null)
   {
     for (int i = 0; i < children.getLength(); i++)
     {
       childNode = children.item(i);
       if ((childNode.getNodeType() == org.w3c.dom.Node.TEXT_NODE) || (childNode.getNodeType() == Node.CDATA_SECTION_NODE))
       {
         childNode.setNodeValue(newValue);
         success = true;
       }
     }
   }
   if (!success)
   {
     Text textNode = node.getOwnerDocument().createTextNode(newValue);
     node.appendChild(textNode);
   }
}

 

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