这是我的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>
</departments>
Department.java
public class Department
{
@XmlAttribute(name = "deptname")
private String name;
@XmlElement(name = "employee")
private List<Employee> employee = new ArrayList<>();//getter and setter//
}
这是我的Departments.java
public class Departments {
List<Department> deptname;
public List<Department> getDeptname() {
return deptname;
}
public void setDeptname(List<Department> deptname) {
this.deptname = deptname;
}
}
这是我的Unmarshalling.java
public class Unmarshalling {
public void testXML() {
try {
File file = new File(
"/home/scrunch/work/workspace/sts/default/EmployeeUnmarshall/src/main/java/OutputXml.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();
}
}
}
我尝试了编组,但是没有得到java对象。我得到了xml格式。我在做休息服务。为此,我需要解组 XML文件,这样我就可以获取Java对象。先生,请给我更新一下。
答案 0 :(得分:0)
我尝试了您的代码并最终出现此错误:
线程“ main”中的异常javax.xml.bind.UnmarshalException:意外元素(uri:“”,local:“部门”)。预期元素为(无)
通过声明Departments
来解决此问题:
@XmlRootElement(name="departments")
public class Departments {
List<Department> deptname;
public List<Department> getDeptname() {
return deptname;
}
public void setDeptname(List<Department> deptname) {
this.deptname = deptname;
}
}
尝试一下