[英]How to deserialize multiple object with xStream
我尝试使用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"));
您可以创建一个类库:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.