gpt4 book ai didi

java - Simplexml 列表不起作用

转载 作者:行者123 更新时间:2023-12-02 05:26:44 27 4
gpt4 key购买 nike

我想使用 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>

这是员工类:

@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

最佳答案

您在定义列表名称时犯了错误:

@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 中,您有一个“Employees”元素类型“Employee”列表。但是在你的java程序中,你将“Employees”列表定义为“list”:

关于java - Simplexml 列表不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25932810/

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