如何使用xStream反序列化多个对象

时间:2015-02-09 10:39:02

标签: java xml deserialization xstream xml-deserialization

我尝试用xStream

读取多个对象

这是我的XML文件

<book>
   <title>abc</title>
   <author>A</author>
   <pagesCount>0</pagesCount>
</book><book>
   <title>qwe</title>
   <author>B</author>
   <pagesCount>0</pagesCount>
</book><book>
   <title>zxc</title>
   <author>C</author>
   <pagesCount>0</pagesCount>
</book>

使用此代码,我可以获得第一本书,你能告诉我如何阅读代码,我能够阅读所有对象(书籍)

XStream xstream = new XStream();
xstream.processAnnotations(Book.class);
Book a = (Book)xstream.fromXML(new File("a.xml"));

1 个答案:

答案 0 :(得分:1)

您可以创建一个类库:

public class Library {
    public List<Book> books = new ArrayList<Book>();
}

并修改您的xml以填充该数据:

<library>
    <books>
        <book>
            <title>abc</title>
            <author>A</author>
            <pagesCount>0</pagesCount>
        </book>
        <book>
            <title>qwe</title>
            <author>B</author>
            <pagesCount>0</pagesCount>
        </book>
        <book>
            <title>zxc</title>
            <author>C</author>
            <pagesCount>0</pagesCount>
        </book>
    </books>
</library>

在你的主要:

public static void main(final String[] args) {

    final String xmlInput = "pathToYourFile";
    try {

        final XStream xstream = new XStream();
        xstream.alias("library", Library.class);
        xstream.alias("book", Book.class);
        final Library a = (Library) xstream.fromXML(new File(xmlInput));
        System.out.println(a);
    } catch (final Exception e) {
        e.printStackTrace();
    }

}
相关问题