There are few ways to parse XML in java :
1. DOM Parser - A DOM is a standard tree structure, where each node contains one of the components from an XML structure. The two most common types of nodes are element nodes and text nodes. Using DOM functions lets you create nodes, remove nodes, change their contents, and traverse the node hierarchy.
2. SAX Parser - Simple API for XML (SAX), an event-driven, serial-access mechanism for accessing XML documents. This protocol is frequently used by servlets and network-oriented programs that need to transmit and receive XML documents, because it is the fastest and least memory-intensive mechanism that is currently available for dealing with XML documents.
With the DOM, the XML is broken down into three main pieces, called entities:
1. Elements (sometimes called tags)
2. Attributes
3. The data (also called values) that the elements and attributes describe
In this post I will demonstrate how to parse an XML file by using DOM parser technique.
Create a sample XML file
<?xml version="1.0"?> <company name="IT"> <employee id="1001"> <name>Ankit Pandoh</name> <salary>100000</salary> <address>Bangalore</address> <contact>99999</contact> </employee> <employee id="1002"> <name>Sumit Malhotra</name> <salary>200000</salary> <address>Delhi</address> <contact>95338</contact> </employee> </company>
Create a class XMLParser to parse and display list of Employees
package parser; 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.NodeList; public class XMLParser { Document dom; String xmlFile; List<Employee> employees = new ArrayList<Employee>(); public static void main(String[] args) { XMLParser parser = new XMLParser(args[0]); parser.parseXML(); parser.displayEmployee(); } XMLParser(String xmlFile) { this.xmlFile = xmlFile; this.dom = getDomParser(this.xmlFile); } /** * obtain an instance of a factory that can give us a document builder. * obtain a new instance of document builder. obtain document object model * from the document builder */ private Document getDomParser(String xmlFile) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = factory.newDocumentBuilder(); dom = docBuilder.parse(xmlFile); } catch (Exception e) { System.out.println(e.getMessage()); } return dom; } private void parseXML() { NodeList employeeNode = dom.getElementsByTagName("employee"); for (int i = 0; i < employeeNode.getLength(); i++) { Employee employee = getEmployee((Element) employeeNode.item(i)); employee.setId(((Element) employeeNode.item(i)).getAttribute("id")); employees.add(employee); } } private Employee getEmployee(Element employeeNode) { String name = getTextValue(employeeNode, "name"); int salary = getIntValue(employeeNode, "salary"); String address = getTextValue(employeeNode, "address"); int contact = getIntValue(employeeNode, "contact"); return new Employee(name, salary, address, contact); } private String getTextValue(Element employeeNode, String tagName) { String textValue = null; NodeList textNode = employeeNode.getElementsByTagName(tagName); if (textNode != null && textNode.getLength() > 0) { textValue = textNode.item(0).getFirstChild().getNodeValue(); } return textValue; } private int getIntValue(Element emp, String tagName) { int textValue = Integer.parseInt(getTextValue(emp, tagName)); return textValue; } private void displayEmployee() { int i = 1; for (Employee employee : employees) { System.out.println("Details of Employee " + i + ":"); System.out.println("ID :" + employee.getId()); System.out.println("Name :" + employee.getName()); System.out.println("Salary :" + employee.getSalary()); System.out.println("Address :" + employee.getAddress()); System.out.println("Contact :" + employee.getContact()); i++; System.out.println(); } } class Employee { private String id; private String name; private int salary; private String address; private int contact; Employee(String name, int salary, String address, int contact) { this.name = name; this.salary = salary; this.address = address; this.contact = contact; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getContact() { return contact; } public void setContact(int contact) { this.contact = contact; } } }
Now, I am going to explain each and every step in detail:
1. Obtain an instance of a factory that can give us a document builder.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
2. Obtain a new instance of document builder.
DocumentBuilder docBuilder = factory.newDocumentBuilder();
3. Obtain document object model from the document builder.
dom = docBuilder.parse(xmlFile)
4. Invoke parseXML(). Get List of EmployeeNodes
NodeList employeeNode = dom.getElementsByTagName("employee")
5. As we can see there are two employee tags in our XML, we will pass one node at a time to getEmployee(Element employeeNode) method which in turn calls the getTextValue(employeeNode, "name") mehod .
6. private String getTextValue(Element employeeNode, String tagName)
{
String textValue = null;
NodeList textNode = employeeNode.getElementsByTagName(tagName);
if (textNode != null && textNode.getLength() > 0)
{
textValue = textNode.item(0).getFirstChild().getNodeValue();
}
return textValue;
}
In this method, we will get the list of element having tagName which is passed from the getTextValue() method. Here this is "name". getFirstChild() will look for the next element tag which is "name" in this case and returns its value.
7. getEmployee() method will return the new Employee object which gets added to the List<Employee>
8. Invoke displayEmployee() to display list of employees object.
9. I have created a Inner class Employee in this case. This can be done separately also.
Output:
Details of Employee 1:
ID :1001
Name :Ankit Pandoh
Salary :100000
Address :Bangalore
Contact :99999
Details of Employee 2:
ID :1002
Name :Sumit Malhotra
Salary :200000
Address :Delhi
Contact :95338
Details of Employee 1:
ID :1001
Name :Ankit Pandoh
Salary :100000
Address :Bangalore
Contact :99999
Details of Employee 2:
ID :1002
Name :Sumit Malhotra
Salary :200000
Address :Delhi
Contact :95338
No comments:
Post a Comment