Download presentation
Presentation is loading. Please wait.
1
WaysInJavaToParseXML
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
2
Parse XML Purpose : populating the XML content into objects and then adding the objects to a list.
3
Sample XML <employees> <employee id="111">
<firstName>Rakesh</firstName> <lastName>Mishra</lastName> <location>Bangalore</location> </employee> <employee id="112"> <firstName>John</firstName> <lastName>Davis</lastName> <location>Chennai</location> <employee id="113"> ………………………………………………….
4
Using DOM Parser (1) The DOM Parser loads the complete XML content into a Tree structure. We iterate through the Node and NodeList to get the content of the XML.
5
Using DOM Parser (2) public class DOMParserDemo {
public static void main(String[] args) throws Exception { //Get the DOM Builder Factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DOM Builder DocumentBuilder builder = factory.newDocumentBuilder();
6
Using DOM Parser (3) //Load and Parse the XML document
//document contains the complete XML as a Tree. Document document = builder.parse( ClassLoader.getSystemResourceAsStream("xml/empl oyee.xml")); List<Employee> empList = new ArrayList<>(); //Iterating through the nodes and extracting the data.
7
Using DOM Parser (4) NodeList nodeList = document.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();
8
Using DOM Parser (5) NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) { Node cNode = childNodes.item(j); //Identifying the child tag of employee encountered. if (cNode instanceof Element) { String content = cNode.getLastChild(). getTextContent().trim(); switch (cNode.getNodeName()) {
9
Using DOM Parser (6) case "firstName": emp.firstName = content; break;
case "lastName": emp.lastName = content; case "location": emp.location = content; }
10
Using DOM Parser (7) } empList.add(emp);
//Printing the Employee list populated. for (Employee emp : empList) { System.out.println(emp);
11
Using DOM Parser (8) } class Employee{ String id; String firstName;
String lastName; String location; @Override public String toString() { return firstName+" "+lastName+"("+id+")"+location;
12
Using DOM Parser (9) } The output for the above will be:
Rakesh Mishra(111)Bangalore John Davis(112)Chennai Rajesh Sharma(113)Pune
13
Other main parsers SAX Parser StAX Parser
You can find sample codes in reference link !!!
14
Reference using-dom-sax-and-stax-parser-in-java/ Drafting out the sample input forms, queries and reports, often helps.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.