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.
The DOM defines several Java interfaces. Here are the most common interfaces −
When you are working with DOM, there are several methods you'll use often −
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
561
Ramu
ECIL
Male
562
Ramya
KBHP
Female
563
Mahi
BHEL
Male
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!!!");
}
}
Enter student ID: 563
STUDENT-DETAILS
===================
student id : 563
student Name : Mahi
Adress : BHEL
Gender : Male