Simple XML
特点:
jar lib文件只有360K左右的大小
它的使用不需要依赖于其他 JAR 文件
通过注解的方式,灵活方便
下面将分节详细介绍Simple的特点和使用方法:
[一]、简单bean的序列化和反序列化
1.java bean
Java代码
package michael.serialization.易做图xml;
import java.util.Date;
import org.易做图framework.xml.Attribute;
import org.易做图framework.xml.Element;
import org.易做图framework.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.序列化
Java代码
public static void main(String[] args) throws Exception {
String xmlpath = "d:/test/michael/易做图_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();
}
}
序列化成功生成的易做图_testvo.xml文件如下:
Xml代码
<myTestVo wife="小小" realName="大大">
<userName>michael</userName>
<bornDate>2011-09-28 17:39:59.432 CST</bornDate>
<height>173.3</height>
</myTestVo>
ps: 注解可以把Java的属性序列化时指定为属性或者节点元素
3.反序列化
把上述生成的XML文件反序列化成Java bean测试代码:
Java代码
public static void main(String[] args) throws Exception {
String xmlpath = "d:/test/michael/易做图_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文件即可,故修改代码如下:
Java代码
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String xmlpath = "d:/test/michael/易做图_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
Java代码
package michael.serialization.易做图xml;
import java.util.Date;
import org.易做图framework.xml.Attribute;
import org.易做图framework.xml.Element;
import org.易做图framework.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;
补充:软件开发 , Java ,