将未知长度的ArrayList添加到XML文件

时间:2014-06-08 07:07:17

标签: java jaxb

我正在使用JAXB将候选tableview保存为XML。

这是当前的输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<candidates>
    <person>
        <name>A</name>
        <weight>100</weight>
    </person>
    <person>
        <name>B</name>
        <weight>120</weight>
    </person>
</candidates>

这是我的文件保存方法:

public void savePerToFile(File file) {
        try {
            JAXBContext context = JAXBContext.newInstance(PerListWrapper.class);
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            PerListWrapper wrapper = new PerListWrapper();
            wrapper.person(perData);
            m.marshal(wrapper, file);
            }
    }

数据来自可观察列表:

private ObservableList<Person> perData = FXCollections.observableArrayList();

我的人包装课:

@XmlRootElement(name = "candidates")
public class PerListWrapper {

    private List<Person> candidates;

    public PerListWrapper() {
        candidates = FXCollections.<Person>observableArrayList();
    }

    public void setPerson(List<Person> candidates) {
        this.candidates = candidates;
    }

    @XmlElement(name = "person")
    public List<Person> getPerson() {
        return this.candidates;
    }
}

现在我希望能够将每日体重跟踪数据从数组列表添加到我的XML中。所有考生都有匹配的考试日。因此输出应该类似于:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<candidates>
    <person>
        <name>A</name>
        <weight>100</weight>
            <tests>
                <num>1</num>
                    <date>2014-04-25</date>
                    <weight>99</weight>
                <num>2</num>
                    <date>2014-04-26</date>
                    <weight>98</weight>
                <num>3</num>
                    <date>2014-04-27</date>
                    <weight>99</weight>
            <tests>
    </person>
    <person>
        <name>B</name>
        <weight>120</weight>
            <tests>
                <num>1</num>
                    <date>2014-04-25</date>
                    <weight>122</weight>
                <num>2</num>
                    <date>2014-04-26</date>
                    <weight>121</weight>
                <num>3</num>
                    <date>2014-04-27</date>
                    <weight>120</weight>
            <tests>
    </person>
</candidates>

有没有简单的方法来实现这一目标?

提前致谢!

0 个答案:

没有答案