1

在这里,我有两个班级“学生”和“课程”:

@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 作为每个课程的键。

4

1 回答 1

0

您可以将 anXmlAdapter用于此用例。AnXmlAdapter允许您以编程方式将对象转换为另一种类型以进行编组/解组。对于您的用例,您将 转换HashMap为具有Course.

于 2013-05-11T09:19:18.513 回答