在这里,我有两个班级“学生”和“课程”:
@XmlRootElement
class Student {
private String name;
private HashMap<String, Course> courses;
public Student() {}
public Student(String name, HashMap<String, Course> courses) {
super();
this.name = name;
this.courses = courses;
}
// -------------------------getters
@XmlAttribute(name="name")
public String getName() {
return name;
}
@XmlElement(name = "course")
public HashMap<String, Course> getCourses() {
return courses;
}
//---------------------------setters
public void setName(String name) {
this.name = name;
}
public void setCourses(HashMap<String, Course> courses) {
this.courses = courses;
}
}
@XmlRootElement
class Course {
private String id;
private String name;
public Course() {}
public Course(String id, String name) {
super();
this.id = id;
this.name = name;
}
@XmlID
@XmlAttribute(name = "id")
public String getId() {
return id;
}
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
我想使用 JaxB 注释将 Student 类序列化为以下内容:
<Student name="David">
<courses>
<Course id="1" name="Fundamentals of Programming"/>
<Course id="2" name="Advanced Programming">
</courses>
</Student>
请注意,我希望 Student 的课程字段为 HashMap,并且在解组序列化对象时使用 id 作为每个课程的键。