Java Reference
In-Depth Information
Converting XML to Java Without JAXB
Problem
The examples in the previous recipe force you to specify the type that you are working with,
and that type has to include mappings in the form of XML annotations. That works fine if in
your SOA you are starting from schema, generating to Java with JAXB, letting it provide the
mappings, and so on. But maybe you're not doing that, or you want a more general-purpose
solution for Java to XML round-trips.
Solution
Try XStream, an open source project available from http://xstream.codehaus.org . It is very
easy to use, it's customizable, and it performs serialization of full object graphs.
You can use the code in Example 3-13 for general-purpose Java to XML round-trips. It
has two methods. The first accepts an object of any type, as long as it implements
java.io.Serializable , and converts it into an XML string using XStream. The second
method accepts a string that has previously been serialized to XML and creates a Java object
out of it.
Example3-13.From Java to XML and back with XStream
package com.soacookbook.ch02.xstream;
import com.soacookbook.ch02.jaxb.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.io.Serializable;
import static java.lang.System.out;
/**
* Shows Java to XML back to Java with no mapping
* using XStream.
*/
public class XMLStreamRoundTrip<T extends Serializable> {
public static void main(String...arg){
//Create a complex object to work with
Book book = new Book();
Author a = new Author();
a.setFirstName("Jacques");
Search WWH ::




Custom Search