I see 3 issues with your code here:
You are retrieving
hireday
instead ofhiredate
tag from XML; should be:if ("hiredate".equals(reader.getLocalName()))
You are retrieving the individual attributes with a namespace where your XML does not have any. Change it to
NULL
, like:int yearAttr = Integer.parseInt(reader.getAttributeValue(null, "year"));
Calendar class in Java considers months starting from 0 (0 being January). Hence your value 12 would move on to the next year. You may want to subtract 1 from the month value to get the desired output.
currentEmployee.setHireDay(yearAttr, monthAttr - 1, dayAttr);
Your modified parseEmployee()
:
public List<Employee> parseEmployee() throws XMLStreamException {
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
if ("employee".equals(reader.getLocalName())) {
currentEmployee = new Employee();
}
if ("staff".equals(reader.getLocalName())) {
employeeList = new ArrayList<>();
}
if ("hiredate".equals(reader.getLocalName())) {
int yearAttr = Integer.parseInt(reader.getAttributeValue(
null, "year"));
int monthAttr = Integer.parseInt(reader.getAttributeValue(
null, "month"));
int dayAttr = Integer.parseInt(reader.getAttributeValue(
null, "day"));
currentEmployee
.setHireDay(yearAttr, monthAttr - 1, dayAttr);
}
break;
case XMLStreamConstants.CHARACTERS:
tagContent = reader.getText().trim();
break;
case XMLStreamConstants.END_ELEMENT:
switch (reader.getLocalName()) {
case "employee":
employeeList.add(currentEmployee);
break;
case "name":
currentEmployee.setName(tagContent);
break;
case "salary":
currentEmployee.setSalary(Double.parseDouble(tagContent));
break;
}
}
}
return employeeList;
}
Now you get the correct output:
Employee { name=Carl Cracker, salary=75000.0, hireDay=Tue Dec 15 00:00:00 IST 1987 }
Employee { name=Harry Hacker, salary=50000.0, hireDay=Sun Oct 01 00:00:00 IST 1989 }
Employee { name=Tony Tester, salary=40000.0, hireDay=Thu Mar 15 00:00:00 IST 1990 }