Getting Dom Tree Elements and their Corresponding XML Fragments
In this section, you will learn to get the elements of a DOM tree and their corresponding XML fragments. Each element of dom tree has a node level starting with '0'. Here the DOM tree elements and their corresponding XML fragments are displayed on the console.
Description of the program:
This program helps you to retrieve the elements of a DOM tree and their corresponding XML fragments on the console. To parse the xml file you need the DocumentBuilder and DoucnemtBuilderFactory. With the help of this you create a NodeList through the getElementByTagName() method. The NodeList helps you in getting the length and Element. For getting the node name you use the getNodeName() method. The transform() method displays the data source and the given destination. This program uses the "System.out" to display the data on the console.
Here is the XML File: Employee-Detail2.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-Detail> |
Here is the Java File: DisplayElementNodes.java
import java.io.*;
|
Output of this program:
C:\vinod\xml>javac DisplayElementNodes.java C:\vinod\xml>java DisplayElementNodes Enter a XML file name: Employee-Detail2.xml Node no: 0 is Employee-Detail Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> Node no: 1 is Employee Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> Node no: 2 is Emp_Id Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Emp_Id> E-001 </Emp_Id> Node no: 3 is Emp_Name Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Emp_Name> Vinod </Emp_Name> Node no: 4 is Emp_E-mail Its corresponding xml representation: <?xml version="1.0" encoding="UTF-8"?><Emp_E-mail> [email protected] </Emp_E-mail> |