将列表保存到XMLFile

时间:2016-03-22 18:39:43

标签: java xml

我想将ArrayList保存到XML文件中。实际上我尝试了但是我刚刚保存了一个完整的列表对象而没有任何<>。它看起来像this,我希望它看起来像

<title>XYZ</title>
<description>XYZ</description>

这是我已经尝试过的:

public class Book {

    public String title;
    public String author;
    public double price;
    public String description;

    public static ArrayList<String> entires = new ArrayList<String>();

    public void setTitle(String title){
        this.title=title;
    }

    public void setAuthor(String author){
        this.author=author;
    }


    public void setPrice(double price){
        this.price=price;
    }

    public void setDescription(String description){
        this.description = description;
    }

    public String toString(){
        return title+"\n"+author+"\n"+description+"\n"+"Price: "+price+"$"+"\n";
    }

}

 public class FileOperations {

    private Book book = new Book();

    public void saveList() throws FileNotFoundException {
        FileOutputStream fileOutputStream = new FileOutputStream("books.xml");
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        XMLEncoder xmlEncoder = new XMLEncoder(bufferedOutputStream);
        xmlEncoder.writeObject(book.entires);
        xmlEncoder.close();
    }
}

0 个答案:

没有答案