Employees.xml:
Employee.java
Java Example program to parse XML using DOM parser:
DOMParserDemo.java
Output:
Employee.java
- package javaXMLParsing;
- public class Employee {
- String id;
- String firstName;
- String lastName;
- String location;
- @Override
- public String toString() {
- return firstName+" "+lastName+"("+id+")"+location;
- }
- }
Java Example program to parse XML using DOM parser:
DOMParserDemo.java
- package javaXMLParsing;
- import java.util.ArrayList;
- import java.util.List;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.Node;
- import org.w3c.dom.NodeList;
- public class DOMParserDemo {
- public static void main(String[] args) throws Exception {
- //Create object of DOM Builder Factory class By using
- //DocumentBuilderFactory.newInstance() method
- DocumentBuilderFactory factoryobj =
- DocumentBuilderFactory.newInstance();
- //Create DOM Builder Object from DocumentBuilderFactory object
- DocumentBuilder builder = factoryobj.newDocumentBuilder();
- //Load the XML document and parse it
- Document documentobj =
- builder.parse(
- ClassLoader.getSystemResourceAsStream("javaXMLParsing/Employee.xml"));
- List<Employee> empList = new ArrayList<>();
- //Iterating through the nodes and extracting the data.
- NodeList nodeList = documentobj.getDocumentElement().getChildNodes();
- for (int i = 0; i < nodeList.getLength(); i++) {
- //We have encountered an <employee> tag.
- Node node = nodeList.item(i);
- if (node instanceof Element) {
- Employee emp = new Employee();
- emp.id = node.getAttributes().
- getNamedItem("id").getNodeValue();
- NodeList childNodes = node.getChildNodes();
- for (int j = 0; j < childNodes.getLength(); j++) {
- Node cNode = childNodes.item(j);
- //Identifying the child tag of employee every employee .
- if (cNode instanceof Element) {
- String content = cNode.getLastChild().
- getTextContent().trim();
- switch (cNode.getNodeName()) {
- case "firstName":
- emp.firstName = content;
- break;
- case "lastName":
- emp.lastName = content;
- break;
- case "location":
- emp.location = content;
- break;
- }
- }
- }
- empList.add(emp);
- }
- }
- //Printing the Employee list by using for each loop.
- for (Employee emp : empList) {
- System.out.println(emp);
- }
- }
- }
Output:
- saidesh kilaru(001)Bangalore
- ajay chanukya(002)Chicago
- Vinod Gandrakoti(003)Hyderabad
Bagikan
Java XML parsing using DOM parser
4/
5
Oleh
Kris Kimcil