Wednesday, August 22, 2012

XML Search using DOM

Search Tag Values in XML using DOM



In this article, the DOM (Document Object Model) technique is used to accomplish the given task. But remember that DOM is not the only way you can do this. To read the XML files efficiently you can use XPATH, StAX, SAX and also DOM. I will write a complete article about how you can choose the best method based on your requirement in a coming post comparing all the methods so that you can get an insight about how each method is working.

Here we go...

What is DOM?

DOM was designed as a language-independent object model to hold any XML data, it suits well the two-phase approach of first loading an XML document into the memory and then performing various operations on it.

DOM parses XML into a tree structure. It offers a lot of flexibility to process the XML data based on the composite pattern. To know more about Composite Design Pattern, have a look at my former article here
 
In the DOM, everything in an XML document is a node.

DOM Nodes

The DOM says:

  • The entire document is a document node
  • Every XML element is an element node
  • The text in the XML elements are text nodes
  • Every attribute is an attribute node
  • Comments are comment nodes

Importantly, Text is Always Stored in Text Nodes

A common error in DOM processing is to expect an element node to contain text.

However, the text of an element node is stored in a text node.

For example, <MODEL> 3D model </MODEL> The element node <MODEL> holds a text node with the value "30".
But "30" is not the value of the  <MODEL> element.

This is the example XML file, which is going to be searched for values.



Here is the complete implementation code in Java. I hope you don't want to feel the same pain as I did..



Happy XML searching....

No comments:

Post a Comment