我正在尝试解析员工的XML文件,并且我想用XML中的数据创建所有员工的数组列表,但是当我运行程序并尝试解析XML文件时,给了我一个零点例外。这是我的XML文件:
<?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>
这是我解析XML文件的代码。当我按下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;
}
}
这是我称之为方法的地方:
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) {
}
}
根据异常消息,错误发生在以下代码行:
Document doc = builder.parse(f);
在我的loadEmployees()方法中找到。谁能告诉我我做错了什么?我之前使用的代码非常类似,并且它已经有效了。非常感谢!
答案 0 :(得分:0)
在您的代码中,您没有为employeesParser定义构造函数。 DocumentBuilder和DocumentBuilderFactory的初始化位于名为“employeesParser”的私有方法中。您可以将此初始化代码移动到构造函数中,或者在loadEmployees()方法的开头调用此employeesParser方法。