Dom parser


Dom is an official recommendation of the World Wide Web Consortium (W3C). Java Dom parser api for xml is intended for working with XML as an object graph (a tree like structure) in memory – so called "Document Object Model (DOM)".

Dom parser traverses the input XML file and creates DOM objects corresponding to the nodes in XML file. These DOM objects are linked together in a tree like structure. Once the parser is done with parsing process, you get this tree-like DOM object structure back from it. Now you can traverse the DOM structure back and forth as you want to get/update/delete data from it.

Advantage of DOM parser


Main advantage of using Dom parser are given below:

  • Easy to use with rich api
  • We can insert or delete nodes
  • Traverse in any direction.

Disadvantage of DOM parser


Main disadvantage of using Dom parser are given below:

  • Stores the entire XML document into memory before processing
  • Occupies more memory

When use DOM parser


If we have want to traverse in any direction or/and add/delete a node run time then we should go for Dom parser.

DOM interfaces


Here is some common interfaces used by Dom

  • Node : Base datatype of DOM.
  • Element : Represent element of xml document
  • Attr : Represents an attribute of an element.
  • Text : The real content of an Element or Attr
  • Document : Represents the entire XML document. A Document object is often referred to as a DOM tree.

DOM methods


Here are few commonly used methods of Dom:

  • Document.getDocumentElement() : Returns the root element of the document.
  • Node.getFirstChild() : Returns the first child of a given Node.
  • Node.getLastChild() : Returns the last child of a given Node.
  • Node.getNextSibling() : These methods return the next sibling of a given Node.
  • Node.getPreviousSibling() : Method return the previous sibling of a given Node.
  • Node.getAttribute(attributeName) : Returns the attribute with the specified attribute name.

Dom parser example


In this example we will parse book.xml using DOM parser and populate object of corresponding class with parsed data. The xml which we are going to parse is given below:

book.xml

I made 2 class to hold parsed data of book.xml are given below:

BookCatalog.java

Book.java

I wrote BookDomParser.java which is responsible for parsing and populating object of BookCatalog class. My dom parser code is given below:

BookDomParser.java

I kept 2 constructor in my Dom parser class. Either pass full path of file or Object of InputStream to create an instance of BookDomParser class.

Here is Main class from where I am intiating dom parsing.

DomParserMain.java

Result

Share & Like

About ApnaTutorials.com

ApnaTutorials.com is for Java, J2ee, Html5 and android developers. All tutorials are well explained and are easy to understand. We have tested every tutorials on our developement environment before posting it in public domain.