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 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> Vinod1@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> Deepak3@yahoo.com </Emp_E-mail> </Employee> </Employee-Detail> |
Here is the Java File: GetRootNode.java
import org.w3c.dom.*;
|
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 |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Getting The XML Root Element View All Comments
Post your Comment