首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

XStream XML-Object变换

2012-07-15 
XStream XML-Object转换?package cn.bisoft.java.testimport java.io.Fileimport java.util.Listimport

XStream XML-Object转换
?XStream XML-Object变换XStream XML-Object变换

    package cn.bisoft.java.test;import java.io.File;import java.util.List;import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;import com.thoughtworks.xstream.io.xml.DomDriver;import com.thoughtworks.xstream.io.xml.XppDriver;import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;import com.thoughtworks.xstream.persistence.PersistenceStrategy;import com.thoughtworks.xstream.persistence.XmlArrayList;public class XStreamFacade{private static XStream xstream;public static final String JAXP_DOM_XML = "JAXP DOM";public static final String XPP3_XML_PARSER = "XPP3";public static final String STAX_JSON_PARSER = "Jettison StAX";public static final String WRITER_JSON_PARSER = "Only Writer JSON";public synchronized static XStream getXStream(String driver){if (JAXP_DOM_XML.equals(driver)){xstream = new XStream(new DomDriver());xstream.autodetectAnnotations(true);}else if (XPP3_XML_PARSER.equals(driver)){xstream = new XStream(new XppDriver());xstream.autodetectAnnotations(true);}else if (STAX_JSON_PARSER.equals(driver)){xstream = new XStream(new JettisonMappedXmlDriver());xstream.setMode(XStream.NO_REFERENCES);}else if (WRITER_JSON_PARSER.equals(driver)){xstream = new XStream(new JsonHierarchicalStreamDriver());xstream.setMode(XStream.NO_REFERENCES);}else{xstream = new XStream(new DomDriver());}return xstream;}@SuppressWarnings("unchecked")public void persist(String dir, List objects){PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir));List<?> list = new XmlArrayList(strategy);list.addAll(objects);}}

    ------------
    扩展:
    1.
    XBird

    2.
    XStream.XPATH_RELATIVE_REFERENCES

    (Default) Uses relative XPath references to signify duplicate references. This produces XML with the least clutter.

    XStream.XPATH_ABSOLUTE_REFERENCES
    Uses absolute XPath references to signify duplicate references. This might produce for some situations better readable XML. Note, that XStream will read XML with relative paths as well as with absolute paths independent of the XPATH mode.

    XStream.ID_REFERENCES
    Uses ID references to signify duplicate references. In some scenarios, such as when using hand-written XML, this is easier to work with.

    XStream.NO_REFERENCES
    This disables object graph support and treats the object structure like a tree. Duplicate references are treated as two separate objects and circular references cause an exception. This is slightly faster and uses less memory than the other two modes.

    3.
    转换器

    示例

    XStreamFacade.java

    ?XStream XML-Object变换XStream XML-Object变换
      package cn.bisoft.java.test;import java.io.File;import java.util.List;import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.converters.reflection.ReflectionProvider;import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider;import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;import com.thoughtworks.xstream.io.xml.DomDriver;import com.thoughtworks.xstream.io.xml.XppDriver;import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;import com.thoughtworks.xstream.persistence.PersistenceStrategy;import com.thoughtworks.xstream.persistence.XmlArrayList;/** * XStreamFacade * * <pre> * 提供对XStream的初始化,降低使用XStream API的复杂性. * @link * </pre> * @author tl * @version 1.0, 2011-6-10 */public class XStreamFacade{public static final String JAXP_DOM_XML = "JAXP DOM";public static final String XPP3_XML_PARSER = "XPP3";public static final String STAX_JSON_PARSER = "Jettison StAX";public static final String WRITER_JSON_PARSER = "Only Writer JSON";/** * 获取XStream对象. * * <pre> * 根据驱动获取XStream对象,若没有提供驱动,则默认使用JAXP-DOM驱动. * </pre> * @param driver 驱动名称 * @param isStaticSupported 是否支持静态变量转换 * @return XStream */public synchronized static XStream getXStream(String driver, boolean isStaticSupported){ReflectionProvider reflectProvider = null;if (isStaticSupported){reflectProvider = new EnhancedModeReflectProvider();}else{reflectProvider = new Sun14ReflectionProvider();}if (JAXP_DOM_XML.equals(driver)){xstream = new XStream(reflectProvider, new DomDriver());xstream.autodetectAnnotations(true);System.err.println(xstream.getReflectionProvider());}else if (XPP3_XML_PARSER.equals(driver)){xstream = new XStream(reflectProvider, new XppDriver());xstream.autodetectAnnotations(true);}else if (STAX_JSON_PARSER.equals(driver)){xstream = new XStream(reflectProvider, new JettisonMappedXmlDriver());xstream.setMode(XStream.NO_REFERENCES);}else if (WRITER_JSON_PARSER.equals(driver)){xstream = new XStream(reflectProvider, new JsonHierarchicalStreamDriver());xstream.setMode(XStream.NO_REFERENCES);}else{xstream = new XStream(reflectProvider, new DomDriver());}return xstream;}/** * 持久化对象列表. * * <pre> * 持久化对象列表,存储到指定用户主目录下的指定目录 * </pre> * @param dir 目录 * @param objects 对象列表 */@SuppressWarnings("unchecked")public void persist(String dir, List objects){PersistenceStrategy strategy = new FilePersistenceStrategy(new File(System.getProperty("user.home"), dir));List<?> list = new XmlArrayList(strategy);list.addAll(objects);}// prinvate fields.private static XStream xstream;}

      EnhancedModeReflectProvider.java

      ?XStream XML-Object变换XStream XML-Object变换
        /** * <pre> * Title: EnhancedModeReflectProvider.java * Author:tl * Create: 2011-6-10 下午02:50:18 * Copyright: Copyright (c) 2011 * Company:Shenzhen ***** * <pre> */package cn.bisoft.java.test;import java.lang.reflect.Field;import java.lang.reflect.Modifier;import com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider;/** * <pre> * 支持静态字段转换,但有缺陷,字段不能映射成属性. * </pre> * @author tl * @version 1.0, 2011-6-10 */public class EnhancedModeReflectProvider extends Sun14ReflectionProvider{@Overrideprotected boolean fieldModifiersSupported(Field field){return !(Modifier.isTransient(field.getModifiers()));}}

        ExampleMessageBody.java

        ?XStream XML-Object变换XStream XML-Object变换
          package cn.bisoft.java.test;import java.util.ArrayList;import java.util.Date;import java.util.List;import com.thoughtworks.xstream.annotations.XStreamAlias;import com.thoughtworks.xstream.annotations.XStreamAsAttribute;import com.thoughtworks.xstream.annotations.XStreamInclude;import com.thoughtworks.xstream.annotations.XStreamOmitField;@SuppressWarnings("unused")@XStreamAlias("body")public class ExampleMessageBody{@XStreamAsAttributeprivate static final String type = "example";private String id = "message id";private Date timestamp;/** 当userList节点必须存在是, 需要初始化. 值为空的字段是不会输出到XML的. */@XStreamAlias("users")private List<User> userList = new ArrayList<User>();@XStreamAlias("user")public static class User{@XStreamAsAttributeprivate String id;@XStreamAsAttributeprivate Date birth;@XStreamOmitFieldprivate String password;public String getId(){return id;}public void setId(String id){this.id = id;}public Date getBirth(){return birth;}public void setBirth(Date birth){this.birth = birth;}public String getPassword(){return password;}public void setPassword(String password){this.password = password;}}public String getId(){return id;}public void setId(String id){this.id = id;}public Date getTimestamp(){return timestamp;}public void setTimestamp(Date timestamp){this.timestamp = timestamp;}public List<User> getUserList(){return userList;}public void setUserList(List<User> userList){this.userList = userList;}}

          TestXStream.java

          ?XStream XML-Object变换XStream XML-Object变换
            package cn.bisoft.java.test;import java.util.ArrayList;import java.util.Date;import java.util.List;import com.thoughtworks.xstream.XStream;public class TestXStream{public static void main(String[] args){XStream xstream = XStreamFacade.getXStream(XStreamFacade.JAXP_DOM_XML, true);ExampleMessageBody body = new ExampleMessageBody();body.setId("0");body.setTimestamp(new Date());List<ExampleMessageBody.User> userList = new ArrayList<ExampleMessageBody.User>();ExampleMessageBody.User user = new ExampleMessageBody.User();user.setBirth(new Date());user.setId("tl");user.setPassword("123456");userList.add(user);body.setUserList(userList);xstream.useAttributeFor("type", ExampleMessageBody.class);String xml = xstream.toXML(body);System.out.println(xml);}}

            说明:
            1. 静态字段其实没有必要序列化.
            2. 集合类型通常需要进行初始化.

热点排行