XML Menu


DOM Parser




DOM stands for Document Object Model. The DOM is a programming interface for HTML(HyperText Markup Language) and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated. The DOM API provides the classes to read and write an XML file. DOM reads an entire document. It is useful when reading small to medium size XML files. It is a tree-based parser and occupies more space when loaded into memory. We can insert and delete nodes using the DOM API.

Important features of XML DOM

  1. Any node can have only one parent node. There cannot be a two-parent node for a single node.
  2. A parent node can have more than one child nodes though.
  3. Child nodes can have their child nodes assigned in any numbers.
  4. Child nodes can have other types of nodes assigned to them called “attribute” nodes. These nodes are used to contain some extra characteristics of the node. This node is different than the child node.
  5. The nodes of the same level in a tree are called “sister” nodes.
  6. DOM identifies the structure of information stored in a hierarchy.
  7. DOM is used to establish a relationship between data stored in different nodes.
reading an xml file using DOM parser in java

DOM interfaces

The DOM defines several Java interfaces. Here are the most common interfaces −

  • Node − The base datatype of the DOM.
  • Element − The vast majority of the objects you'll deal with are Elements.
  • Attr − Represents an attribute of an element.
  • Text − The actual content of an Element or Attr.
  • Document − Represents the entire XML document. A Document object is often referred to as a DOM tree.

Common DOM methods

When you are working with DOM, there are several methods you'll use often −

  • 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() − These methods return the previous sibling of a given Node.
  • Node.getAttribute(attrName) − For a given Node, it returns the attribute with the requested name.

Write a java program which takes users id as input and returns the users details by taking the user information from the XML document using DOM parser.

student.xml
<students-details>
<student>
<studentid>561</studentid>
<name>Ramu</name>
<address>ECIL</address>
<gender>Male</gender>
</student>
<student>
<studentid>562</studentid>
<name>Ramya</name>
<address>KBHP</address>
<gender>Female</gender>
</student>
<student>
<studentid>563</studentid>
<name>Mahi</name>
<address>BHEL</address>
<gender>Male</gender>
</student>
</students-details>

SAXParserxml.java
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.util.Scanner;
import java.io.*;

public class DOMParserDemo{public static void main(String[] args) throws Exception{    

	//Create a DocumentBuilder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();     
    DocumentBuilder builder = factory.newDocumentBuilder();     // parser is created     
    Document doc = builder.parse("student.xml"); // file is parsed   

    NodeList list = doc.getElementsByTagName("student");     
    Scanner in = new Scanner(System.in);     
    System.out.print("Enter student ID:\t");    
    int n = in.nextInt();     
    int flag = 0;    
    for(int i = 0; i < list.getLength(); i++){        
        Node node = list.item(i);        
        if(node.getNodeType() == Node.ELEMENT_NODE){            
            Element e = (Element) node;            
            int x=Integer.parseInt(e.getElementsByTagName("studentid").item(0).getTextContent());             
            if(x==n){                System.out.println("\n\n STUDENT-DETAILS");                 
                System.out.println("===================");                 
                System.out.println("student id :\t" + e.getElementsByTagName("studentid").item(0).getTextContent());                 
                System.out.println("student Name :\t" + e.getElementsByTagName("name").item(0).getTextContent());                 
                System.out.println("Adress :\t" + e.getElementsByTagName("address").item(0).getTextContent());                 
                System.out.println("Gender :\t" + e.getElementsByTagName("gender").item(0).getTextContent());                 
                flag=1;                
                break;            
            }            
            else{               
                flag=0;           
            }       
        }  
    }    
    if(flag==0)        
    System.out.println("student Id is not present.Try Again!!!");    
    }
}

Output
Enter student ID:	563

 STUDENT-DETAILS
===================
student id :	563
student Name :	Mahi
Adress :		BHEL
Gender :		Male


Next Topic :SAX Parser