xStream - 第一个应用程序

  • 简述

    在深入了解 XStream 库的细节之前,让我们先看看一个正在运行的应用程序。在这个例子中,我们创建了 Student 和 Address 类。我们将创建一个学生对象,然后将其序列化为 XML 字符串。然后反序列化相同的 XML 字符串以获取回学生对象。
    在其中创建一个名为 XStreamTester 的 java 类文件 C:\>XStream_WORKSPACE.
    File: 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 int rollNo;
       private String firstName;
       private String lastName;
       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();
       }
    }
    
    Verify the Result
    使用编译类 javac 编译器如下 -
    
    C:\XStream_WORKSPACE>javac XStreamTester.java
    
    现在运行 XStreamTester 以查看结果 -
    
    C:\XStream_WORKSPACE>java XStreamTester
    
    Verify the output as follows
    
    <?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 使用 Stax pull 解析器(可从 java 6 获得)并且是一个快速的 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);