【发布时间】:2020-07-05 17:44:02
【问题描述】:
我有这个特定的 xml 文件(以那种确切的格式),我试图用 JAXB 解析它 因为属性都在一行上,所以它看不到它们,并且在我的主函数中将所有字段都返回为 null。如何正确解析 xml 格式?
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee firstName="Asya" id="2" lastname="Olshansky"/>
</employees>
这是员工的代码
@XmlRootElement(name = "employee")
@XmlAccessorType (XmlAccessType.FIELD)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String firstName;
private String lastName;
public Employee() {
super();
}
//Setters and Getters
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
员工代码:
@XmlRootElement(name = "employees")
@XmlAccessorType(XmlAccessType.FIELD)
public class Employees {
@XmlElement(name = "employee")
List<Employee> employees = null;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> list) {
this.employees = list;
}
}
这是主要执行:
public static void main(String[] args)
{
String fileName = "employee.xml";
jaxbXmlFileToObject(fileName);
}
private static void jaxbXmlFileToObject(String fileName) {
File xmlFile = new File(fileName);
JAXBContext jaxbContext;
try
{
jaxbContext = JAXBContext.newInstance(Employees.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Employees employees = (Employees) jaxbUnmarshaller.unmarshal(xmlFile);
for(Employee e: employees.getEmployees() )
System.out.println(e);
}
catch (JAXBException e)
{
e.printStackTrace();
}
}
【问题讨论】:
标签: java xml-parsing jaxb