我想阅读并解析包含使用SimpleXML框架的员工信息的XML文件。这是我的XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Employee>
<age>29</age>
<name>Pankaj</name>
<gender>Male</gender>
<role>Java Developer</role>
</Employee>
<Employee>
<age>35</age>
<name>Lisa</name>
<gender>Female</gender>
<role>CEO</role>
</Employee>
</Employees>
这是Employees类:
@Root
public class Employees {
@ElementList(inline = true)
private List<Employee> list;
public List<Employee> getList() {
return list;
}
}
这是Employee类:
@Root
public class Employee {
@Element
private String name;
@Element
private String gender;
@Element
private int age;
@Element
private String role;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return " Name=" + this.name + " Age="
+ this.age + " Gender=" + this.gender + " Role=" + this.role;
}
}
但是当我尝试读取并解析XML文件时,会发生异常。这是输出:
Exception in thread "main" org.simpleframework.xml.core.ElementException: Element 'Employee' does not have a match in class Employees at line 3
答案 0 :(得分:1)
您在定义列表名称时犯了错误:
@Root
public class Employees {
@ElementList(inline = true)
private List<Employee> Employees; //The list name should match with xml list name."
public List<Employee> getList() {
return list;
}
}
在XML中,您有一个“员工”列表,其中包含“员工”类型的元素。但是在您的java程序中,您将“Employees”列表定义为“list”:
答案 1 :(得分:1)
我发现了问题。我必须用这个:
@ElementList(inline = true, entry="Employee")
因为没有这个,框架认为元素类名是&#34;条目&#34;。
答案 2 :(得分:0)
您可以尝试为Employees对象中使用的列表添加类型。 但最好还添加代码如何阅读xml文件(我现在没有足够的声誉在评论中提问你)
@Root
class Employees {
@ElementList(inline = true, type = Employee.class)
private List<Employee> list;
public List<Employee> getList() {
return list;
}
}
对于问题中的第一个示例,在添加
之前@ElementList(entry = "Employee")
private List<Employee> list;
预期的XML文件在下面(和@ElementList(type = Employee.class),我删除了inline = true)
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<list>
<employee>
<age>29</age>
<name>Pankaj</name>
<gender>Male</gender>
<role>Java Developer</role>
</employee>
<employee>
<age>35</age>
<name>Lisa</name>
<gender>Female</gender>
<role>CEO</role>
</employee>
</list>
</employees>