我正在使用 dom4j 通过使用 XPath 技术来选择所需节点来读取 XML。考虑一下我的 XML 如下所示:
<Emp_Dir>
<Emp_Classification type ="Permanent" >
<Emp id= "1">
<name>jame</name>
<Emp_Bio>
<age>12</age>
<height>5.4</height>
<weight>78</weight>
</Emp_Bio>
<Empployment_History>
<job>
<salary>2000</salary>
<designation>senior developer</designation>
<duration>2years</duration>
</job>
<job>
<salary>1000</salary>
<designation>developer</designation>
<duration>3years</duration>
</job>
</Empployment_History>
</Emp>
.
.
.
</Emp_Classification>
<Emp_Classification type ="Contract" >
.
.
.
</Emp_Classification>
<Emp_Classification type ="PartTime" >
.
.
.
</Emp_Classification>
</Emp_Dir>
注意:上面的 XML 对你来说可能看起来很难看,但我只是为了理解和保持我的项目的保密性而创建这个虚拟文件
我想要的目标是获取每个永久员工的就业历史,为此我设法通过使用以下 XPath Epression 获取永久员工的所有“Emp”节点:
//Emp_Dir/Emp_Classification[@type='Permanent']/Emp
获取和存储节点的代码如下所示:
List<? extends Node> lstprmntEmps = document.selectNodes("//Emp_Dir/Emp_Classification/[@type='Permanent']/Emp");
ArrayList<Employee> Employees = new ArrayList<Employee>();//Employee is my custom class
for (Node node : lstprmntEmps)
{
Employees.add(ParseEmployee(node));//ParseEmployee(. . .) is my custom function that pareses emp XML and return Employee object
}
现在我想问以下三个问题:
- 如何获取每个员工的 ID 属性?
- 如何获取每个员工的姓名元素?
- 最后但也是最重要的一个,我需要指定什么 XPath 才能获得每个员工的 Job 节点?我试过folwoing但没有成功:(
node.selectNodes("/Emp/Empployment_History/job"); //这返回零节点(或) node.selectNodes("//Emp/Empployment_History/job");// 这返回的节点比预期的多