XStream入門應用程式


在進入XStream庫的細節之前,讓我們來看看應用程式操作。在這個例子中,我們建立Student和Address類。還將建立一個Student物件,然後將其序列化到一個XML字串。然後反序列化的同一個XML字串,以重新獲得學生物件。

建立一個名為XStreamTester的Java類檔案在 C:\>XStream_WORKSPACE.

檔案: XStreamTester.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

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());

      Student student = tester.getStudentDetails();
      
	  //Object to XML Conversion
      String xml = xstream.toXML(student);
      System.out.println(formatXml(xml));

      //XML to Object Conversion		
      Student student1 = (Student)xstream.fromXML(xml);
      System.out.println(student1);
   }	

   private Student getStudentDetails(){
      Student student = new Student();
      student.setFirstName("Mahesh");
      student.setLastName("Parashar");
      student.setRollNo(1);
      student.setClassName("1st");

      Address address = new Address();
      address.setArea("H.No. 16/3, Preet Vihar.");
      address.setCity("Delhi");
      address.setState("Delhi");
      address.setCountry("India");
      address.setPincode(110012);

      student.setAddress(address);
      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 xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
         StreamResult res =  new StreamResult(new ByteArrayOutputStream());            
         serializer.transform(xmlSource, res);
         return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());
      }catch(Exception e){         
         return xml;
      }
   }
}

class Student {
   private String firstName;
   private String lastName;
   private int rollNo;
   private String className;
   private Address address;

   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   public String getClassName() {
      return className;
   }
   public void setClassName(String className) {
      this.className = className;
   }
   public Address getAddress() {
      return address;
   }
   public void setAddress(Address address) {
      this.address = address;
   }

   public String toString(){
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("Student [ ");
      stringBuilder.append("\nfirstName: ");
      stringBuilder.append(firstName);
      stringBuilder.append("\nlastName: ");
      stringBuilder.append(lastName);
      stringBuilder.append("\nrollNo: ");
      stringBuilder.append(rollNo);
      stringBuilder.append("\nclassName: ");
      stringBuilder.append(className);
      stringBuilder.append("\naddress: ");
      stringBuilder.append(address);
      stringBuilder.append(" ]");
      return stringBuilder.toString();
   }
}

class Address {
   private String area;
   private String city;
   private String state;
   private String country;
   private int pincode;

   public String getArea() {
      return area;
   }
   public void setArea(String area) {
      this.area = area;
   }
   public String getCity() {
      return city;
   }
   public void setCity(String city) {
      this.city = city;
   }
   public String getState() {
      return state;
   }
   public void setState(String state) {
      this.state = state;
   }
   public String getCountry() {
      return country;
   }
   public void setCountry(String country) {
      this.country = country;
   }
   public int getPincode() {
      return pincode;
   }
   public void setPincode(int pincode) {
      this.pincode = pincode;
   }
   public String toString(){
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("\nAddress [ ");
      stringBuilder.append("\narea: ");
      stringBuilder.append(area);
      stringBuilder.append("\ncity: ");
      stringBuilder.append(city);
      stringBuilder.append("\nstate: ");
      stringBuilder.append(state);
      stringBuilder.append("\ncountry: ");
      stringBuilder.append(country);
      stringBuilder.append("\npincode: ");	
      stringBuilder.append(pincode);
      stringBuilder.append(" ]");
      return stringBuilder.toString();
   }
}

驗證結果

使用javac編譯器編譯如下類:

C:\XStream_WORKSPACE>javac XStreamTester.java

現在執行XStreamTester看到結果:

C:\XStream_WORKSPACE>java XStreamTester

驗證輸出

<?xml version="1.0" encoding="UTF-8"?>
<Student>
  <firstName>Mahesh</firstName>
  <lastName>Parashar</lastName>
  <rollNo>1</rollNo>
  <className>1st</className>
  <address>
    <area>H.No. 16/3, Preet Vihar.</area>
    <city>Delhi</city>
    <state>Delhi</state>
    <country>India</country>
    <pincode>110012</pincode>
  </address>
</Student>

Student [ 
firstName: Mahesh
lastName: Parashar
rollNo: 1
className: 1st
address: 
Address [ 
area: H.No. 16/3, Preet Vihar.
city: Delhi
state: Delhi
country: India
pincode: 110012 ] ]

記住以下步驟

以下是這裡要考慮的重要步驟。

第1步:建立XStream物件。

通過它傳遞一個StaxDriver建立XStream物件。StaxDriver使用SAX解析器(可從Java6),一個快速的XML解析器。

XStream xstream = new XStream(new StaxDriver());

第2步:序列化物件到XML。

使用toXML() 方法來獲取物件的XML字串表示。

//Object to XML Conversion
String xml = xstream.toXML(student);

第3步:反序列化XML獲得物件。

使用 fromXML()方法來從XML物件。

//XML to Object Conversion		
Student student1 = (Student)xstream.fromXML(xml);