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.*;
|
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 |