Getting all XML Elements

In this section, you will learn to retrieve all elements of the XML file using the DOM APIs.

Getting all XML Elements

Getting all XML Elements 

     

In this section, you will learn to retrieve all elements of the XML file using the DOM APIs. This APIs provides some constructors and methods which helps us to parse the XML file and retrieve all elements.

Description of program:

The following program helps you in getting all XML elements displayed on the console. This program asks for a xml file name and checks its availability. whether the given file exists or not in the same directory. So, you need a XML file (Employee-Detail.xml) that contains some elements. Program parses the xml file using the parse() method and creates a Document object Tree.  DocumentBuilder object  helps you to get features to parse the XML file.  After parsing the XML file a NodeList is created using the getElementsByTagName().This NodeList object creates element.  Elements name are retrieved using the getNodeName() method. 

Here is the XML File: Employee-Detail.xml

<?xml version = "1.0" ?>
<Employee-Detail>

<Employee>
<Emp_Id> E-001 </Emp_Id>
<Emp_Name> Vinod </Emp_Name>
<Emp_E-mail> [email protected] </Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-002 </Emp_Id>
<Emp_Name> Amit </Emp_Name>
<Emp_E-mail> [email protected] </Emp_E-mail>
</Employee>

<Employee>
<Emp_Id> E-003 </Emp_Id>
<Emp_Name> Deepak </Emp_Name>
<Emp_E-mail> [email protected] </Emp_E-mail>
</Employee>

</Employee-Detail>

Here is Java File: DOMElements.java

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class DOMElements{
 static public void main(String[] arg){
 try {
 BufferedReader bf = new BufferedReader(
   new 
InputStreamReader(System.in));
 System.out.print("Enter XML File name: ");
 String xmlFile = bf.readLine();
 File file = new File(xmlFile);
 if(file.exists()){
 // Create a factory
 DocumentBuilderFactory factory = 
   DocumentBuilderFactory.newInstance
();
 // Use the factory to create a builder
 DocumentBuilder builder = factory.newDocumentBuilder();
 Document doc = builder.parse(xmlFile);
 // Get a list of all elements in the document
 NodeList list = doc.getElementsByTagName("*");
 System.out.println("XML Elements: ");
 for (int i=0; i<list.getLength(); i++) {
 // Get element
 Element element = (Element)list.item(i);
 System.out.println(element.getNodeName());
 }
 }
 else{
 System.out.print("File not found!");
 }
 }
 catch (Exception e) {
 System.exit(1);
 }
 }
}

Download this example.

Output of this program:

C:\vinod\xml>javac DOMElements.java

C:\vinod\xml>java DOMElements
Enter XML File name: Employee-Detail.xml
XML Elements:
Employee-Detail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail
Employee
Emp_Id
Emp_Name
Emp_E-mail