Simple XML_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Simple XML

Simple XML

 2011/9/29 8:03:01  sjsky  http://sjsky.iteye.com  我要评论(0)
  • 摘要:之前曾写过一blog:XStream序列化JAVA对象为XML以及反序列化(http://sjsky.iteye.com/blog/784434),今天介绍另一个JavaBean<->XML之间序列化和反序列化的轻量级工具:Simple官网:http://simple.sourceforge.net/home.php截止目前最新版本(附近可下载):simple-xml-2.6.1.jar特点:jarlib文件只有360K左右的大小它的使用不需要依赖于其他JAR文件通过注解的方式
  • 标签:XML

之前曾写过一blog : XStream序列化JAVA对象为XML以及反序列化 (http://sjsky.iteye.com/blog/784434),今天介绍另一个Java Bean<->XML 之间序列化和反序列化的轻量级工具:Simple

官网:http://simple.sourceforge.net/home.php

截止目前最新版本(附近可下载):simple-xml-2.6.1.jar

?

特点:

  • jar lib文件只有360K左右的大小
  • 它的使用不需要依赖于其他 JAR 文件
  • 通过注解的方式,灵活方便

?

下面将分节详细介绍Simple的特点和使用方法

?

[一]、简单bean的序列化和反序列化

?

????? 1.java bean

?

package michael.serialization.simplexml;

import java.util.Date;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * 
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root
public class MyTestVo {

    @Element
    private String userName;

    @Attribute
    private String wife;

    @Attribute
    private String realName;

    @Element
    private Date bornDate;

    @Element
    private Double height;

    public String toString() {
        return "MyTestVo : [ userName = " + userName + " , wife = " + wife
                + " , realName = " + realName + " , height = " + height
                + " , bornDate = " + bornDate + " ]";
    }
    //省略set get等方法
    ......

}
?

????? 2.序列化

public static void main(String[] args) throws Exception {
        String xmlpath = "d:/test/michael/simple_testvo.xml";

        MyTestVo vo = new MyTestVo();
        vo.setUserName("michael");
        vo.setRealName("大大");
        vo.setWife("小小");
        vo.setHeight(173.3d);
        vo.setBornDate(new Date());

        try {
            Serializer serializer = new Persister();
            File result = new File(xmlpath);
            serializer.write(vo, result);
        } catch (Exception e) {
            e.printStackTrace();
        }

}

??? 序列化成功生成的simple_testvo.xml文件如下:

?

<myTestVo wife="小小" realName="大大">
   <userName>michael</userName>
   <bornDate>2011-09-28 17:39:59.432 CST</bornDate>
   <height>173.3</height>
</myTestVo>

?? 可根据注解可以把Java的属性序列化为属性或者节点元素

?

??? 3.反序列化

?

??? 把上述生成的XML文件反序列化成Java bean测试代码:

?

 public static void main(String[] args) throws Exception {
        String xmlpath = "d:/test/michael/simple_testvo.xml";
        
        Serializer serializer = new Persister();
        File source = new File(xmlpath);
        try {
            MyTestVo vo = serializer.read(MyTestVo.class, source);
            System.out.println(vo);
        } catch (Exception e) {
            e.printStackTrace();
        }
}

? 如果XML中包括中文字符有可能反序列化时会报错,以utf-8的编码读取XML文件即可,故修改代码如下:

?

 /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String xmlpath = "d:/test/michael/simple_testvo.xml";

        Serializer serializer = new Persister();

        try {
            InputStreamReader is = new InputStreamReader(new FileInputStream(
                    xmlpath), "utf-8");
            PropertyList parseVo = serializer.read(PropertyList.class, is);
            System.out.println(parseVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

?

? 运行反序列化,打印Java bean信息如下:

MyTestVo : [ userName = michael , wife = 小小小 , realName = 大大 , height = 173.3 , bornDate = Wed Sep 28 17:39:59 CST 2011 ]
?

[二]、自定义节点名称

????? 1.java bean

package michael.serialization.simplexml;

import java.util.Date;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root(name = "MyTest")
public class MyTestVo {

    @Element
    private String userName;

    @Attribute(name = "MyWife")
    private String wife;

    @Attribute
    private String realName;

    @Element(name = "born")
    private Date bornDate;

    @Element
    private Double height;

    @Override
    public String toString() {
        return "MyTestVo : [ userName = " + userName + " , wife = " + wife
                + " , realName = " + realName + " , height = " + height
                + " , bornDate = " + bornDate + " ]";
    }
    //set get ......
}
?

????? 2.序列化

?

?? 序列化后生成的simple_testvo.xml文件如下:

?

<MyTest MyWife="小小" realName="大大">
   <userName>michael</userName>
   <born>2011-09-28 21:47:37.455 CST</born>
   <height>173.3</height>
</MyTest>

?? 可以和之前的序列化XML文件对比下,看看区别在哪里。

?

????? 3.反序列化

?

?????? 运行反序列化程序后的打印结果如下:

MyTestVo : [ userName = michael , wife = 小小 , realName = 大大 , height = 173.3 , bornDate = Wed Sep 28 21:47:37 CST 2011 ] ?

[三]、嵌套对象

?

????? 1.java bean

?

package michael.serialization.simplexml;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root
public class ConfigurationVo {
    @Element
    private ServerVo server;

    @Attribute
    private int id;

    public ServerVo getServer() {
        return server;
    }

    public int getId() {
        return id;
    }

    public void setServer(ServerVo pServer) {
        server = pServer;
    }

    public void setId(int pId) {
        id = pId;
    }

}

?

package michael.serialization.simplexml;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root
public class ServerVo {
    @Attribute
    private int port;

    @Element
    private String host;

    @Element
    private SecurityVo security;

    public int getPort() {
        return port;
    }

    public String getHost() {
        return host;
    }

    public SecurityVo getSecurity() {
        return security;
    }

    public void setPort(int pPort) {
        port = pPort;
    }

    public void setHost(String pHost) {
        host = pHost;
    }

    public void setSecurity(SecurityVo pSecurity) {
        security = pSecurity;
    }

}
?
package michael.serialization.simplexml;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root
public class SecurityVo {
    @Attribute
    private boolean ssl;

    @Element
    private String keyStore;

    public boolean isSsl() {
        return ssl;
    }

    public String getKeyStore() {
        return keyStore;
    }

    public void setSsl(boolean pSsl) {
        ssl = pSsl;
    }

    public void setKeyStore(String pKeyStore) {
        keyStore = pKeyStore;
    }

}
?

????? 2.序列化

?

/**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String xmlpath = "d:/test/michael/simple_testvo.xml";

        SecurityVo security = new SecurityVo();
        security.setSsl(true);
        security.setKeyStore("Michael");

        ServerVo server = new ServerVo();
        server.setHost("sjsky.iteye.com");
        server.setPort(8088);
        server.setSecurity(security);

        ConfigurationVo config = new ConfigurationVo();
        config.setId(10000);
        config.setServer(server);

        Serializer serializer = new Persister();
        try {
            File xmlFile = new File(xmlpath);
            serializer.write(config, xmlFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
}

?? 运行上述方法,序列化生成的XML文件如下:

?

<configurationVo id="10000">
   <server port="8088">
      <host>sjsky.iteye.com</host>
      <security ssl="true">
         <keyStore>Michael</keyStore>
      </security>
   </server>
</configurationVo>
?

????? 3.反序列化的方法和之前的一致,自己 可以 测试下结果是否正确。

?

[四]、可选的非强制性的元素或属性

?

????? 1.java bean

package michael.serialization.simplexml;

import java.util.Date;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root
public class MyTestVo {

    @Element
    private String userName;

    // 不是每个人都有妻子的 吼吼
    @Attribute(required = false)
    private String wife;

    @Attribute
    private String realName;

    // 不想泄露年龄噢
    @Element(required = false)
    private Date bornDate;

    @Element
    private Double height;

    @Override
    public String toString() {
        return "MyTestVo : [ userName = " + userName + " , wife = " + wife
                + " , realName = " + realName + " , height = " + height
                + " , bornDate = " + bornDate + " ]";
    }

   //省略setter getter方法

}

?

????? 2.序列化

 /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String xmlpath = "d:/test/michael/simple_testvo.xml";

        MyTestVo vo = new MyTestVo();
        vo.setUserName("michael");
        vo.setRealName("大大");
        vo.setHeight(173.3d);

        Serializer serializer = new Persister();
        try {
            File xmlFile = new File(xmlpath);
            serializer.write(vo, xmlFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
}

?? 运行序列化程序后生成的XML文件如下:

?

<myTestVo realName="大大">
   <userName>michael</userName>
   <height>173.3</height>
</myTestVo>

????? 3.反序列化

?

???? 运行反序列化程序后打印结果如下:

?

MyTestVo : [ userName = michael , wife = null , realName = 大大 , height = 173.3 , bornDate = null ] ?

[五]、List<Object>处理

????? 1.java bean

package michael.serialization.simplexml;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root
public class PropertyList {

    @ElementList
    private List<EntryVo> list;

    @Attribute
    private String name;

    public List<EntryVo> getList() {
        return list;
    }

    public String getName() {
        return name;
    }

    public void setList(List<EntryVo> pList) {
        list = pList;
    }

    public void setName(String pName) {
        name = pName;
    }

    @Override
    public String toString() {
        return "PropertyList : [ name = " + name + " , EntryVo list size = "
                + list.size() + " ] .";
    }
}
?
package michael.serialization.simplexml;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root
public class EntryVo {

    @Attribute
    private String name;

    @Element
    private String value;

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public void setName(String pName) {
        name = pName;
    }

    public void setValue(String pValue) {
        value = pValue;
    }

}
?

????? 2.序列化

 /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        String xmlpath = "d:/test/michael/simple_testvo.xml";

        Serializer serializer = new Persister();

        try {
            PropertyList vo = initBean();
            serializer.write(vo, new File(xmlpath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static PropertyList initBean() {
        PropertyList vo = new PropertyList();
        vo.setName("Wife List");
        List<EntryVo> subList = new ArrayList<EntryVo>();
        EntryVo subvo = new EntryVo();
        subvo.setName("A");
        subvo.setValue("福晋");
        subList.add(subvo);
        subvo = new EntryVo();
        subvo.setName("B");
        subvo.setValue("侧福晋");
        subList.add(subvo);
        subvo = new EntryVo();
        subvo.setName("C");
        subvo.setValue("小三");
        subList.add(subvo);
        subvo = new EntryVo();
        subvo.setName("D");
        subvo.setValue("二奶");
        subList.add(subvo);
        vo.setList(subList);
        return vo;

    }
?

?运行序列化程序后生成的XML文件如下:

?

<propertyList name="Wife List">
   <list class="java.util.ArrayList">
      <entryVo name="A">
         <value>福晋</value>
      </entryVo>
      <entryVo name="B">
         <value>侧福晋</value>
      </entryVo>
      <entryVo name="C">
         <value>小三</value>
      </entryVo>
      <entryVo name="D">
         <value>二奶</value>
      </entryVo>
   </list>
</propertyList>

?

????? 3.反序列化,运行结果打印对象信息如下:

?

PropertyList : [ name = Wife List , EntryVo list size = 4 ] .

????? 4.修改注解@ElementList的参数

?

    @ElementList(name = "WifeList", entry = "wife")
    private List<EntryVo> list;

??? 序列化后生成的XML文件如下:

?

<propertyList name="Wife List">
   <WifeList class="java.util.ArrayList">
      <wife name="A">
         <value>福晋</value>
      </wife>
      <wife name="B">
         <value>侧福晋</value>
      </wife>
      <wife name="C">
         <value>小三</value>
      </wife>
      <wife name="D">
         <value>二奶</value>
      </wife>
   </WifeList>
</propertyList>
?

?

?

[六]、 inline 参数用法

?

????? 1.java bean

?????? 以上节中得bean为基础修改注解如下:

@Root
public class PropertyList {

    @ElementList(name = "WifeList", entry = "wife", inline = true)
    private List<EntryVo> list;

    @Attribute
    private String name;

    public List<EntryVo> getList() {
        return list;
    }

    public String getName() {
        return name;
    }

    public void setList(List<EntryVo> pList) {
        list = pList;
    }

    public void setName(String pName) {
        name = pName;
    }

    @Override
    public String toString() {
        return "PropertyList : [ name = " + name + " , EntryVo list size = "
                + list.size() + " ] .";
    }
}
?

????? 2.序列化后生成的XML文件如下:

?

<propertyList name="Wife List">
   <wife name="A">
      <value>福晋</value>
   </wife>
   <wife name="B">
      <value>侧福晋</value>
   </wife>
   <wife name="C">
      <value>小三</value>
   </wife>
   <wife name="D">
      <value>二奶</value>
   </wife>
</propertyList>

? ? 和上节生成的文件相比,XML结构少了一个层次。

?

[七]、构造函数的注解处理

????? 1.java bean

?

package michael.serialization.simplexml;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
@Root
public class EntryVo {
    public EntryVo(@Attribute(name = "name")
    String name, @Element(name = "value")
    String value) {
        this.name = name;
        this.value = value;
    }

    @Attribute(name = "name")
    private String name;

    @Element(name = "value")
    private String value;

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }

    public void setName(String pName) {
        name = pName;
    }

    public void setValue(String pValue) {
        value = pValue;
    }

    @Override
    public String toString() {
        return "EntryVo : [ name = " + name + ", value = " + value + " ].";
    }
}

?

????? 2.序列化

?

????? 生成的XML文件如下:

<entryVo name="blog">
<value>http://sjsky.iteye.com</value>
</entryVo> ?

????? 3.反序列化

?

????? 反序列化生成的bean的信息打印如下:

?

EntryVo : [ name = blog, value = http://sjsky.iteye.com ].

?

ps:如果java bean有参数的构函数,需要在构造函数的参数前也加上相应的注解,否则在反序列化时会出错。

?

本文就先介绍到这,下次再介绍其他运用事例。

?

?

本文连接:http://sjsky.iteye.com/blog/1182057

?

?

转载请注明来自:Michael's blog @ http://sjsky.iteye.com

----------------------------- 分 ------------------------------ 隔 ------------------------------ 线 ------------------------------

?

?

?

  • simple-xml-2.6.1.jar (360.1 KB)
  • 下载次数: 0
发表评论
用户名: 匿名