2010-03-15 39 views
0

尋找將Java DTO轉換爲XML並在使用GWT時轉回的最佳方法。我看到GWT在它的客戶端軟件包中有XMLParser,它是一個DOM解析器。我正在尋找更像JAXB類型的插件功能,我可以使用GWT。將XML轉換爲Java DTO並返回GWT

回答

2

我真的很喜歡XStream的,但它會在GWT服務器端只工作

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()); 
    } 

}