【问题标题】:How to deserialize multiple object with xStream如何使用 xStream 反序列化多个对象
【发布时间】:2015-02-09 10:39:01
【问题描述】:

我尝试使用 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"));

【问题讨论】:

  • 这个文件是你生成的吗?我希望有一个“外部”标签,可能是 &lt;books&gt;,然后您会将 xml 反序列化为一个包含书籍对象列表的类。
  • 我使用以下代码创建此文件:`FileOutputStream file = new FileOutputStream("a.xml", true); PrintWriter print = new PrintWriter(file); print.write(xstream.toXML(object));

标签: java xml deserialization xstream xml-deserialization


【解决方案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();
    }

}

【讨论】:

  • 你能解释一下我必须做什么,因为我从 5 小时开始使用 xStream,我对它没有很好的了解。谢谢
  • okey 我什么都懂,只是一个简单的问题,如何以添加 library 的方式重写我的代码,我要编写的代码是 FileOutputStream file = new FileOutputStream("a.xml", true ); PrintWriter print = new PrintWriter(file); print.write(xstream.toXML(object));
  • @user3613534 我已经编辑了添加主要方法的答案,您唯一需要添加的是别名。
  • 是的,但只有当我转到我的 xml 文件并手动编写 时,它才会自动运行
  • @user3613534 你可以手动或使用代码stackoverflow.com/questions/13741751/…
猜你喜欢
  • 2011-07-23
  • 2015-04-13
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
相关资源
最近更新 更多