tags:

views:

196

answers:

1

Looking for best approach to convert Java DTO to XML and back while using GWT. I saw GWT has XMLParser in its client package which is a DOM Parser. I'm looking for more like a JAXB kind of plugin feature that I can use with GWT.

A: 

I really like XStream, but it will work only on GWT server side

package xstream;

import com.thoughtworks.xstream.XStream;

import java.util.HashMap;
import java.util.Map;

public class XstreamUtil {
    private static Map streams= new HashMap();

    public static String toXml(Object o) {
        return getStream(o.getClass()).toXML(o);
    }

    public static  T fromXml(Class c, String xml) {
        return (T) getStream(c).fromXML(xml);
    }

    public static  T copyOf(Class clazz, Object o) {
        return (T) getStream(clazz).fromXML(getStream(o.getClass()).toXML(o));
    }

    private static synchronized XStream getStream(Class c) {
        if (!streams.containsKey(c.getPackage())) {
            XStream x = new XStream();
            streams.put(c.getPackage(), x);
        }
        return (XStream) streams.get(c.getPackage());
    }

}
Maciek Kreft