I'm trying to parse an XML file of employees, and with the data in the XML I want to create an array list of all of the employees, but when I run the program and try to parse the XML file, it gives me a Null Point Exception. This is my XML file:
<?xml version="1.0"?>
<employees>
<employee>
<name>Roberta Robertson</name>
<manager>false</manager>
</employee>
<employee>
<name>Taylor Meyers</name>
<manager>true</manager>
</employee>
<employee>
<name>John Mayer</name>
<manager>true</manager>
</employee>
</employees>
This is my code for parsing the XML file. I call the method when I press a certain button in my GUI.
public class employeesParser {
private DocumentBuilder builder;
private XPath path;
private void employeesParser()
throws ParserConfigurationException
{
// create the documentbuiler and path
DocumentBuilderFactory dbfactory
= DocumentBuilderFactory.newInstance();
builder = dbfactory.newDocumentBuilder();
XPathFactory xpfactory = XPathFactory.newInstance();
path = xpfactory.newXPath();
}
// read the file
public ArrayList<Employee> loadEmployees(String fileName)
throws SAXException, IOException, XPathExpressionException
{
//parsing the file
File f = new File(fileName);
Document doc = builder.parse(f);
//reading the file, extracting the employees, add employees to ArrayList
int employeeCount = Integer.parseInt(path.evaluate(
"count(/employees/employee)", doc));
for (int i = 1; i <= employeeCount; i++)
{
String employeeName = path.evaluate(
"/employees/employee[" + i + "]/name", doc);
boolean managerStatus = Boolean.parseBoolean(path.evaluate(
"employees/employee[" + i + "]/manager", doc));
Employee employee = new Employee(employeeName, managerStatus);
employeeList.add(employee);
}
return employeeList;
}
}
This is where I call the method:
private void addEmployeeXMLActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
employeesParser parser = new employeesParser();
employeeList = parser.loadEmployees("employees.xml");
}
catch (SAXException|IOException|XPathExpressionException e) {
}
}
According to the exception message, the error occurs at this line of code:
Document doc = builder.parse(f);
which is found in my loadEmployees() method. Can anyone tell me what I'm doing wrong? I've used code very similar to this before and it has worked. Thanks a lot!