把java对象转化成xml文件保存
导入的包
jettison-1.0.1.jar
xpp3_min-1.1.4c.jar
xstream-1.3.1.jar
userInfo:
package com.lb;
public class userInfo {
private String name;
private String phoneNumber;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Name : "+this.name+
"\nPhoneNumber : "+this.phoneNumber+
"\nAddress : "+this.address;
}
}
userinfo2xml:
package com.lb;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.thoughtworks.xstream.XStream;
import com.user.userInfo;
public class userinfo2xml {
public static void main(String[] args)
{
// 初始化BEAN对象
userInfo userInfo = new userInfo();
userInfo.setName("XXX");
userInfo.setPhoneNumber("XXXXXXXXX");
userInfo.setAddress("北京昌平区");
// 初始化XStream对象
XStream xStream = new XStream();
// xStream.omitField(Employee .class, "name"); //定义某一个属性的值不进行xml序列化。
// xStream.useAttributeFor(String.class); // 对所有String类型的字段定义为属性tag显示
// xStream.useAttributeFor("name",String.class);// 对所有String类型的字段名成为name
// 定义为属性tag显示,读取的时候获取不了该值
try {
FileOutputStream fs = new FileOutputStream("d:/userInfo.xml");
xStream.toXML(userInfo, fs);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
}