[英]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.