1 回答
TA贡献1775条经验 获得超8个赞
根据 XML 文档,您只能有一个根元素,因此应将 xml 更改为:
<?xml version="1.0" encoding="UTF-8"?>
<departments>
<deptname name="Research">
<employee>
<eid>r-001</eid>
<ename>Dinesh R</ename>
<age>35</age>
<deptcode>d1</deptcode>
<deptname>Research</deptname>
<salary>20000</salary>
</employee>
</deptname>
<deptname name="Sales">
<employee>
<eid>s-001</eid>
<ename>Kanmani S</ename>
<age>35</age>
<deptcode>d2</deptcode>
<deptname>Sales</deptname>
<salary>30000</salary>
</employee>
</deptname>
<deptname name="Delivery">
<employee>
<eid>d-001</eid>
<ename>Kanchana M</ename>
<age>35</age>
<deptcode>d3</deptcode>
<deptname>Delivery</deptname>
<salary>20000</salary>
</employee>
</deptname>
</departments>
然后,您需要一个类部门来阅读该文章:
@XmlRootElement(name="departments")
public class Departments {
List<Department> deptname;
// Getters and setters
}
测试用例是:
@Test
public void testXML() {
try {
File file = new File("./src/main/resources/employee.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Departments.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Departments departments = (Departments) jaxbUnmarshaller.unmarshal(file);
System.out.println(departments);
} catch (JAXBException e) {
e.printStackTrace();
}
}
其次,您没有“研究”或“销售”或“交付”属性,您有一个可以采用任何字符串值的属性“name”,因此您需要更改实现:
public class Department {
@XmlAttribute(name = "name")
private String name;
@XmlElement(name = "employee")
private List<Employee> employee = new ArrayList<>();
// Getters and setters
}
添加回答
举报