JAXB解析多student节点XML时对象被覆盖仅保留最后一条如何解决
问题根源
- 包装类
Students中仅定义了单个Student对象,解析多个<student>标签时后续值会覆盖前值,最终仅保留最后一条记录。 Student类字段名和XML标签名不匹配(Java字段是大写开头Id,XML标签是小写<id>),且缺少必要的JAXB注解指定字段和标签的映射关系。- 主程序的列表存储逻辑错误,不需要把包装类本身存入列表,直接读取包装类内的学生列表即可。
修改后的代码
1. Student.java
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import lombok.Data; @Data @XmlAccessorType(XmlAccessType.FIELD) public class Student { // 匹配XML中的小写id标签 @XmlElement(name = "id") private long id; private String firstName; private String lastName; private String company; }
2. Students.java(包装类)
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; import lombok.Data; @Data @XmlRootElement(name = "students") @XmlAccessorType(XmlAccessType.FIELD) public class Students { // 声明为List存储多个student标签对应的数据 @XmlElement(name = "student") private List<Student> studentList; }
3. ParsingXML.java(主程序)
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; import java.util.List; public class ParsingXML { public static void main(String[] args) { try { File xmlFile = new File("Student.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Students.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Students students = (Students) jaxbUnmarshaller.unmarshal(xmlFile); // 直接获取包装类内的学生列表即可 List<Student> studentList = students.getStudentList(); // 遍历输出所有学生 for (Student student : studentList) { System.out.println(student); } } catch (JAXBException e) { e.printStackTrace(); } } }
附加说明
开头的反射警告是高版本JDK对JAXB实现的访问限制导致的,不影响功能,如果要消除可以在JVM启动参数中添加--add-opens java.base/java.lang=ALL-UNNAMED,或者升级jaxb-runtime到2.3.3以上版本即可解决。
内容的提问来源于stack exchange,提问作者Rakshan Premsagar Kapikad
相关产品推荐
相关产品推荐

