gpt4 book ai didi

java - 通过使用 JAXB 解码将 XML 转换为对象

转载 作者:行者123 更新时间:2023-12-02 10:09:33 25 4
gpt4 key购买 nike

我想通过使用 JAXB 解码将 XML 转换为 java。

这是我的employee.xml。我尝试转换,但显示错误 javax.xml.bind.UnmarshalException

<?xml version="1.0" encoding="UTF-8"?>
<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>

最佳答案

根据XML documentation ,您只能有一个根元素,因此您应该将 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>

那么你需要一个 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();
}
}

其次,您没有“研究”或“销售”或“交付”属性,您有一个可以采用任何字符串值的属性“名称”,因此您需要更改实现:

public class Department {
@XmlAttribute(name = "name")
private String name;

@XmlElement(name = "employee")
private List<Employee> employee = new ArrayList<>();

// Getters and setters
}

关于java - 通过使用 JAXB 解码将 XML 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55103735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com