【发布时间】:2016-04-14 11:00:03
【问题描述】:
我有一个这种格式的 xml 文件:
<Employee>
<EmployeeID>10</EmployeeID>
<Name>David</Name>
<Department>Service</Department>
</Employee>
我有一个大的 xml 文件,它只包含这种格式的员工。我想要的是使用 xPath 从文件中选择节点,然后为每个条目创建一个 Java 对象:
public class Employee {
String name;
String department;
int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
这是我目前所拥有的。我似乎无法弄清楚如何最好地检索我需要的所有信息,并创建对象:
public void parseFile(String fileName) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document document = null;
try {
builder = factory.newDocumentBuilder();
document = builder.parse(new File(fileName));
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
List<Employee> employees = getEmployeesFromXml(document, xPath);
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private List<Employee> getEmployeesFromXml(Document document, XPath xPath) {
List<Employee> list = new ArrayList<Employee>();
try {
// Create an expression that retrieves the values from xml
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return null;
}
【问题讨论】:
-
您无法使用 xPath 解析 XML 文件。 xPath 是一种查询语言,可在现有加载的 XML 文档 (DOM) 中选择节点。