English 中文(简体)
XStream - First Application
  • 时间:2024-12-22

XStream - First Apppcation


Previous Page Next Page  

Before going into the details of the XStream pbrary, let us see an apppcation in action. In this example, we ve created Student and Address classes. We will create a student object and then seriapze it to an XML String. Then de-seriapze the same XML string to obtain the student object back.

Create a java class file named XStreamTester in 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;

pubpc class XStreamTester {

   pubpc 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;
   }
   
   pubpc static String formatXml(String xml) {
   
      try {
         Transformer seriapzer = SAXTransformerFactory.newInstance().newTransformer();
         
         seriapzer.setOutputProperty(OutputKeys.INDENT, "yes");
         seriapzer.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());            
         
         seriapzer.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;

   pubpc String getFirstName() {
      return firstName;
   }
   
   pubpc void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   
   pubpc String getLastName() {
      return lastName;
   }
   
   pubpc void setLastName(String lastName) {
      this.lastName = lastName;
   }
   
   pubpc int getRollNo() {
      return rollNo;
   }
   
   pubpc void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   
   pubpc String getClassName() {
      return className;
   }
   
   pubpc void setClassName(String className) {
      this.className = className;
   }
   
   pubpc Address getAddress() {
      return address;
   }
   
   pubpc void setAddress(Address address) {
      this.address = address;
   }
   
   pubpc String toString() {
      StringBuilder stringBuilder = new StringBuilder();
      
      stringBuilder.append("Student [ ");
      stringBuilder.append("
firstName: ");
      stringBuilder.append(firstName);
      stringBuilder.append("
lastName: ");
      stringBuilder.append(lastName);
      stringBuilder.append("
rollNo: ");
      stringBuilder.append(rollNo);
      stringBuilder.append("
className: ");
      stringBuilder.append(className);
      stringBuilder.append("
address: ");
      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;

   pubpc String getArea() {
      return area;
   }

   pubpc void setArea(String area) {
      this.area = area;
   }

   pubpc String getCity() {
      return city;
   }

   pubpc void setCity(String city) {
      this.city = city;
   }

   pubpc String getState() {
      return state;
   }

   pubpc void setState(String state) {
      this.state = state;
   }

   pubpc String getCountry() {
      return country;
   }

   pubpc void setCountry(String country) {
      this.country = country;
   }

   pubpc int getPincode() {
      return pincode;
   }

   pubpc void setPincode(int pincode) {
      this.pincode = pincode;
   }

   pubpc String toString() {

      StringBuilder stringBuilder = new StringBuilder();

      stringBuilder.append("
Address [ ");
      stringBuilder.append("
area: ");
      stringBuilder.append(area);
      stringBuilder.append("
city: ");
      stringBuilder.append(city);
      stringBuilder.append("
state: ");
      stringBuilder.append(state);
      stringBuilder.append("
country: ");
      stringBuilder.append(country);
      stringBuilder.append("
pincode: ");	
      stringBuilder.append(pincode);
      stringBuilder.append(" ]");

      return stringBuilder.toString();
   }
}

Verify the Result

Compile the classes using javac compiler as follows −

C:XStream_WORKSPACE>javac XStreamTester.java

Now run the XStreamTester to see the result −

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
   ] 
]

Steps to Remember

Following are the important steps to be considered here.

Step 1: Create an XStream Object

Create an XStream object by passing it a StaxDriver. StaxDriver uses Stax pull parser (available from java 6) and is a fast xml parser.

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

Step 2: Seriapze the Object to XML

Use toXML() method to get the XML string representation of the object.

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

Step 3: De-seriapze XML to Get the Object

Use fromXML() method to get the object from the XML.

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