How to Parse XML file in Java
In this tutorial, we are going to learn about the Parsing XML file in Java.
We can Parse XML file using Java DOM parser and Java SAX parser.
We will learn about the DOM parser.
Java DOM Parser
DOM parser parses the whole XML file and creates a DOM object within the memory. It models an XML enters a tree structure for straightforward traversal and manipulation. In DOM everything in an XML file may be a node. The node represents a component of an XML file.
The XML file is as follow:-
<?xml version="1.0"?> <class> <Employee> <id>1</id> <firstname>Rohit</firstname> <lastname>Rajawat</lastname> <salary>50K</salary> </Employee> <Employee> <id>2</id> <firstname>Sachin</firstname> <lastname>Tehere</lastname> <salary>80K</salary> </Employee> <Employee> <id>3</id> <firstname>Sanjay</firstname> <lastname>Patel</lastname> <salary>100K</salary> </Employee> </class>
The Example java code to parse the XML file is as follows:
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; public class FXML { public static void main(String argv[]) { try { File F = new File("MYFile.xml"); //an instance of factory that gives a document builder DocumentBuilderFactory D = DocumentBuilderFactory.newInstance(); //an instance of builder to parse the specified xml file DocumentBuilder Dbulid = D.newDocumentBuilder(); Document DoC = Dbulid.parse(F); DoC.getDocumentElement().normalize(); System.out.println("Root element: " + DoC.getDocumentElement().getNodeName()); NodeList NL = DoC.getElementsByTagName("employee"); for (int i = 0; i < NL.getLength(); i++) { Node NoD = NL.item(i); System.out.println("\nNode Name :" + NoD.getNodeName()); if (NoD.getNodeType() == Node.ELEMENT_NODE) { Element E = (Element) NoD; System.out.println("Employee id: "+ E.getElementsByTagName("id").item(0).getTextContent()); System.out.println("First Name: "+ E.getElementsByTagName("firstname").item(0).getTextContent()); System.out.println("Last Name: "+ E.getElementsByTagName("lastname").item(0).getTextContent()); System.out.println("salary: "+ E.getElementsByTagName("salary").item(0).getTextContent()); } } } catch (Exception e) { e.printStackTrace(); } } }
OUTPUT:-
Root element: class Node Name: employee employee id: 1 First Name: Rohit Last Name: Rajawat salary: 50K Node Name: employee employee id: 2 First Name: Sachin Last Name: Tehere salary: 80K Node Name: employee employee id: 3 First Name: Sanjay Last Name: Patel salary: 100K
Leave a Reply