Specifying root and child nodes with JAXB

折月煮酒 提交于 2019-12-02 10:44:10

You are very close. You need to change how you name your xmlElement for myNotes in MyNotes class. Also MyNote should not have a note field itself (according to your desired xml). Your edited classes would look like this (I also removed the logging statements for my convenience):

@XmlType(propOrder = { "to", "from", "heading", "body"})
@XmlRootElement(name = "note")
public class MyNote {

    private String to;
    private String from;
    private String heading;
    private String body;

    public String getTo() {
        return to;
    }

    @XmlElement(name = "to")
    public void setTo(String to) {
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    @XmlElement(name = "from")
    public void setFrom(String from) {
        this.from = from;
    }

    public String getHeading() {
        return heading;
    }

    @XmlElement(name = "heading")
    public void setHeading(String heading) {
        this.heading = heading;
    }

    public String getBody() {
        return body;
    }

    @XmlElement(name = "body")
    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return  to + from + heading + body;
    }

}

and MyNotes:

@XmlRootElement(name = "MyNotes")
public class MyNotes {

    private List<MyNote> myNotes = new ArrayList<>();

    public MyNotes() {
    }

    public List<MyNote> getMyNotes() {
        return myNotes;
    }

    @XmlElement(name = "note")
    public void setMyNotes(List<MyNote> myNotes) {
        this.myNotes = myNotes;
    }

    public void add(MyNote myNote) {
        myNotes.add(myNote);
    }

    @Override
    public String toString() {
        StringBuffer str = new StringBuffer();
        for (MyNote note : this.myNotes) {
            str.append(note.toString());
        }
        return str.toString();
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!