Getting The XML Root Element

After reading this section, you will be able to retrieve a root element from the XML document.

Getting The XML Root Element

     

After reading this section, you will be able to retrieve a  root element from the XML document.  The JAXP (Java APIs for XML Processing) provides a common interface for creating and using xml files using the standard SAX, DOM and XSLTs. Here you will see the given example to use DOM interface. 

Description of program:

You need a XML document (file). Both Java and the XML file are kept in the same directory. This program takes a XML file as a String at the console . If the given file exists then it parses the document using parse() method . Before parsing the XML document you need a DocumentBuilder object. For creating this first of all you create a DocumentBuilderFactory. After parsing the XML document you get  the node element using getDocumentElement() method. To get the root element use the getNodeName() method.  

Here is the video insturction " How to get root node of XML in Java?":

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 the Java File: GetRootNode.java

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

public class GetRootNode{
  public static void main(String[] args) {
  try{
  BufferedReader bf = new BufferedReader(
  
new InputStreamReader(System.in));
  System.out.print("Enter xml file name: ");
  String str = bf.readLine();
  File file = new File(str);
  if (file.exists()){
  DocumentBuilderFactory fact = 
   DocumentBuilderFactory.newInstance
();
  DocumentBuilder builder = fact.newDocumentBuilder();
  Document doc = builder.parse(str);
  Node node = doc.getDocumentElement();
  String root = node.getNodeName();
  System.out.println("Root Node: " + root);
  }
  else{
  System.out.println("File not found!");
  }
  }
  catch(Exception e){}
  }
}

Download this example.

Output of the program:

C:\vinod\xml>javac GetRootNode.java

C:\vinod\xml>java GetRootNode
Enter xml file name: Employee-Detail.xml
Root Node: Employee-Detail

 

Download source code of the project in Eclipse Project format

Ads