使用JAXB仅将最后一个元素写入XML

时间:2015-03-04 07:00:21

标签: java xml jaxb

我想将来自数据库的数据写入xml文件。有5个数据。问题是JAXB只将最后的数据写入XML文件。这是我的代码;

public void createXmlFile() {
    String path = Labels.getLabel("zk.file.xmlfilepath");
    Kitap k = new Kitap();
    File xmlFile = new File(path);

    try {
        if (xmlFile.createNewFile()) {
            System.out.println("Kitaplar.xml file created.");
        } else {
            System.err.println("Kitaplar.xml file can't created!");
        }

        JAXBContext jaxbContext = JAXBContext.newInstance(Kitap.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        for (int i = 0; i < kitapList.size(); i++) {
            k.setKitapId(kitapList.get(i).getKitapId());
            k.setKitapad(kitapList.get(i).getKitapad());
            k.setYazarad(kitapList.get(i).getYazarad());
            k.setKitapdurum(kitapList.get(i).getKitapdurum());
            k.setKitaptur(kitapList.get(i).getKitaptur());
            k.setKitapImage(kitapList.get(i).getKitapimage());

            jaxbMarshaller.marshal(k, xmlFile);
            jaxbMarshaller.marshal(k, System.out);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    }

}

Kitap.java

@XmlRootElement
public class Kitap {

private int kitapId;
private String kitapad;
private String yazarad;
private String kitaptur;
private String kitapdurum;
private byte[] kitapImage;

public int getKitapId() {
    return kitapId;
}

@XmlAttribute
public void setKitapId(int kitapId) {
    this.kitapId = kitapId;
}

public String getKitapad() {
    return kitapad;
}

@XmlElement
public void setKitapad(String kitapad) {
    this.kitapad = kitapad;
}

public String getYazarad() {
    return yazarad;
}

@XmlElement
public void setYazarad(String yazarad) {
    this.yazarad = yazarad;
}

public String getKitaptur() {
    return kitaptur;
}

@XmlElement
public void setKitaptur(String kitaptur) {
    this.kitaptur = kitaptur;
}

public String getKitapdurum() {
    return kitapdurum;
}

@XmlElement
public void setKitapdurum(String kitapdurum) {
    this.kitapdurum = kitapdurum;
}

public byte[] getKitapImage() {
    return kitapImage;
}

@XmlElement
public void setKitapImage(byte[] kitapImage) {
    this.kitapImage = kitapImage;
}

}

我的代码有什么问题?为什么只有最后一个元素在xml文件上写?

1 个答案:

答案 0 :(得分:1)

请阅读JAXB编组的规范:https://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/Marshaller.html#marshal%28java.lang.Object,%20java.io.File%29

更重要的是:

File to be written. If this file already exists, it will be overwritten. 

你正在循环中进行编组,所以基本上你每次都用最后一个元素覆盖文件。

一种解决方案是创建一个包含Kitap个对象列表的包装器对象,并封送所述包装器对象。