Use xstream to serialize Java objects into XML (2)

Source: Internet
Author: User

 Add xstream support

Follow these steps to add an xstream library to a new project:

1. Select the new project in Eclipse project explorer and select Properties from the project menu, as shown in Figure 5 ).

Figure 5. Add an xstream Library

2. Click Add external jars and select the xstream-1.2.2.jar from the xstream_home/lib folder.

3. Click OK (as shown in Figure 6 ).

Figure 6. Added support for xstream

Figure 7 shows the project after xstream is added.

Serialized object

This simple example demonstrates how to use xstream to serialize/deserialize objects, including two classes: writer and reader. The writer class uses the xstream API to serialize an object of the employee type into XML and store it in a file (as shown in Listing 1 ).

Listing 1. Writer. Java

 

package com.samples;import java.io.FileNotFoundException;import java.io.FileOutputStream;import com.thoughtworks.xstream.*;public class Writer { public static void main(String[] args) { Employee e = new Employee(); //Set the properties using the setter methods //Note: This can also be done with a constructor. //Since we want to show that XStream can serialize //even without a constructor, this approach is used. e.setName("Jack"); e.setDesignation("Manager"); e.setDepartment("Finance"); //Serialize the object XStream xs = new XStream(); //Write to a file in the file system try { FileOutputStream fs = new FileOutputStream("c:/temp/employeedata.txt"); xs.toXML(e, fs); } catch (FileNotFoundException e1) { e1.printStackTrace(); } }}

 

Reader class reads the file, deserializes XML, and loads data into a Java object (as shown in Listing 2 ).

Reference from: http://java.chinaitlab.com/XMLBeans/777336_2.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.