隱式集合混疊時使用的集合是表示在XML無需顯示根。例如,在我們的例子中,我們需要一個接一個,但不是在根節(jié)點來顯示每一個節(jié)點。讓我們再次修改例子,下面的代碼添加到它。
xstream.addImplicitCollection(Student.class, "notes");
讓我們使用XStream測試上述對象序列化。
創(chuàng)建一個Java類名為XStreamTester在文件 C:\>XStream_WORKSPACE\com\yiibai\xstream.
File: XStreamTester.java
package com.yiibai.xstream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.stream.StreamResult; import org.xml.sax.InputSource; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.StaxDriver; public class XStreamTester { public static void main(String args[]){ XStreamTester tester = new XStreamTester(); XStream xstream = new XStream(new StaxDriver()); xstream.alias("student", Student.class); xstream.alias("note", Note.class); xstream.aliasField("name", Student.class, "studentName"); xstream.addImplicitCollection(Student.class, "notes"); Student student = tester.getStudentDetails(); //Object to XML Conversion String xml = xstream.toXML(student); System.out.println(formatXml(xml)); } private Student getStudentDetails(){ Student student = new Student("Mahesh"); student.addNote(new Note("first","My first assignment.")); student.addNote(new Note("second","My Second assignment.")); return student; } public static String formatXml(String xml){ try{ Transformer serializer= SAXTransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); Source下一篇:XStream類混疊