|
| 1 | + |
| 2 | +package com.journaldev.xml.sax; |
| 3 | + |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +import org.xml.sax.Attributes; |
| 8 | +import org.xml.sax.SAXException; |
| 9 | +import org.xml.sax.helpers.DefaultHandler; |
| 10 | + |
| 11 | +import com.journaldev.xml.Employee; |
| 12 | + |
| 13 | +public class MyHandler extends DefaultHandler { |
| 14 | + |
| 15 | + // List to hold Employees object |
| 16 | + private List<Employee> empList = null; |
| 17 | + private Employee emp = null; |
| 18 | + private StringBuilder data = null; |
| 19 | + |
| 20 | + // getter method for employee list |
| 21 | + public List<Employee> getEmpList() { |
| 22 | + return empList; |
| 23 | + } |
| 24 | + |
| 25 | + boolean bAge = false; |
| 26 | + boolean bName = false; |
| 27 | + boolean bGender = false; |
| 28 | + boolean bRole = false; |
| 29 | + |
| 30 | + @Override |
| 31 | + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { |
| 32 | + |
| 33 | + if (qName.equalsIgnoreCase("Employee")) { |
| 34 | + // create a new Employee and put it in Map |
| 35 | + String id = attributes.getValue("id"); |
| 36 | + // initialize Employee object and set id attribute |
| 37 | + emp = new Employee(); |
| 38 | + emp.setId(Integer.parseInt(id)); |
| 39 | + // initialize list |
| 40 | + if (empList == null) |
| 41 | + empList = new ArrayList<>(); |
| 42 | + } else if (qName.equalsIgnoreCase("name")) { |
| 43 | + // set boolean values for fields, will be used in setting Employee variables |
| 44 | + bName = true; |
| 45 | + } else if (qName.equalsIgnoreCase("age")) { |
| 46 | + bAge = true; |
| 47 | + } else if (qName.equalsIgnoreCase("gender")) { |
| 48 | + bGender = true; |
| 49 | + } else if (qName.equalsIgnoreCase("role")) { |
| 50 | + bRole = true; |
| 51 | + } |
| 52 | + // create the data container |
| 53 | + data = new StringBuilder(); |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public void endElement(String uri, String localName, String qName) throws SAXException { |
| 58 | + if (bAge) { |
| 59 | + // age element, set Employee age |
| 60 | + emp.setAge(Integer.parseInt(data.toString())); |
| 61 | + bAge = false; |
| 62 | + } else if (bName) { |
| 63 | + emp.setName(data.toString()); |
| 64 | + bName = false; |
| 65 | + } else if (bRole) { |
| 66 | + emp.setRole(data.toString()); |
| 67 | + bRole = false; |
| 68 | + } else if (bGender) { |
| 69 | + emp.setGender(data.toString()); |
| 70 | + bGender = false; |
| 71 | + } |
| 72 | + |
| 73 | + if (qName.equalsIgnoreCase("Employee")) { |
| 74 | + // add Employee object to list |
| 75 | + empList.add(emp); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + @Override |
| 80 | + public void characters(char ch[], int start, int length) throws SAXException { |
| 81 | + data.append(new String(ch, start, length)); |
| 82 | + } |
| 83 | +} |
0 commit comments