In this section, you will see how to parse a XML document in java.
In this section, you will see how to parse a XML document in java.In this tutorial, we will discuss about how to parse(retrieve data) DOM Document.
The XML DOM views an XML document as a tree-structure. In this program, we read the XML file and print the data.
The steps are as follows:
Get a list of Employee elements from the DOM and count the no of persons by getLength() of list.
For each employee element get the Name, ID and Age and get the child nodes of every employee by using getChildNodes() and getNodeValues().
The xml file used for the Parsing is Employees.xml.
<?xml version="1.0" encoding="UTF-8"?> <Roseindia> <Employee type="permanent"> <Name>Ravi</Name> <Id>3</Id> <Age>28</Age> </Employee> <Employee type="contract"> <Name>Rajesh</Name> <Id>4</Id> <Age>30</Age> </Employee> <Employee type="permanent"> <Name>sanjeev</Name> <Id>5</Id> <Age>27</Age> </Employee> </Roseindia> |
The Read_PrintFile.java.
import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class Read_PrintXMLFile{ public static void main (String argv []){ try { DocumentBuilderFactory odbf = DocumentBuilderFactory.newInstance(); DocumentBuilder odb = odbf.newDocumentBuilder(); Document odoc = odb.parse (new File("Employees.xml")); odoc.getDocumentElement ().normalize (); System.out.println ("Root element of the doc is " + odoc.getDocumentElement().getNodeName()); NodeList LOP = odoc.getElementsByTagName("Employee"); int totalPersons =LOP.getLength(); System.out.println("Total no of people : " + totalPersons); for(int s=0; s<LOP.getLength() ; s++) { Node FPN =LOP.item(s); |
Output:
C:\>java Read_PrintXMLFile Root element of the doc is Roseindia Total no of people : 3 Name : Ravi Id : 3 Age : 28 Name : Rajesh Id : 4 Age : 30 Name : sanjeev Id : 5 Age : 27 |