File xmlFile = new File(xmlpath);
serializer.write(config, xmlFile);
} catch (Exception e) {
e.printStackTrace();
}
}
运行上述方法,序列化生成的XML文件如下:
Xml代码
3.反序列化的方法和之前的一致,自己 可以 测试下结果是否正确。
[四]、可选的非强制性的元素或属性
1.java bean
Java代码
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.序列化
Java代码
/**
* @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文件如下:
Xml代码
3.反序列化
运行反序列化程序后打印结果如下:
MyTestVo : [ userName = michael , wife = null , realName = 大大 , height = 173.3 , bornDate = null ]
[五]、List