Member-only story
1. What is xstream?
XStream is a simple Java-based library that serializes Java objects into XML and vice versa (i.e., can easily convert Java objects to xml documents to and from them).
XStream Features:
- Easy to use — XStream’s API provides a high-level look and feel to simplify common use cases.
- There is no need to create a mapping — XStream’s API provides default mapping for most object serialization.
- performance — XStream is fast and has a low memory footprint, making it ideal for large object graphs or systems.
- Clean XML — XStream creates a clean and compact XML result, which is easy to read.
- There is no need to modify the object — XStream serializes internal fields, such as private and final fields, with support for non-public and internal classes. The default constructor is not mandatory.
- Full object graph support — XStream allows you to keep repeated references encountered in the object model and supports circular references.
- Customizable conversion strategies — Customization policies can allow specific types of customizations to be represented as XML registrations.
- Security framework — XStream provides a fair control over the types of ungrouping to prevent manipulating input security issues.
- Error messages — When an exception occurs due to malformed XML, XStream throws a uniform exception that provides a detailed diagnosis to resolve the issue.
- Another output format — XStream supports other output formats such as JSON.
2. XStream basic usage
Create an XStream object
Create an XStream object by passing a StaxDriver through it. StaxDriver uses the SAX parser (available from Java 6), a fast XML parser.
XStream xstream = new XStream(new StaxDriver());
Serialize objects to XML
Use the toXML() method to get the XML string representation of the object.
String xml = xstream.toXML(student);
Deserialize the XML to get the object
Use the fromXML() method to extract the data from the XML object.