我創建了XML文件作爲我創建的對象(稱爲「triple」)的數據庫。 當我嘗試添加新對象(同一類型的)的另一行時,它會刪除上一行。 如何添加而不刪除? (下前行)如何在Java中將對象添加到xml中?
下面是代碼:
public class RDB {
File file;
String filepath;
JAXBContext jaxbContext;
Marshaller jaxbMarshaller;
RDB(){
filepath = "RDB.xml";
file = new File(filepath);
StreamResult result = new StreamResult(file);
try {
jaxbContext = JAXBContext.newInstance(triple.class);
jaxbMarshaller = jaxbContext.createMarshaller();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void addToXml(triple t){
try {
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(t, file);
jaxbMarshaller.marshal(t, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
public static void main(String argv[]) {
RDB r = new RDB();
r.addToXml(new triple(1,2,3));
r.addToXml(new triple(4,5,6));
}
與三階級是這樣的:
public class triple implements Serializable {
private static final long serialVersionUID = 1L;
private double x, y;
private int z;
triple(double x , double y, int z){
this.x = x;
this.y = y;
this.z = z;
}
謝謝!
請使用Java命名約定,即「triple」類應該被命名爲「Triple」類。 –