xStream将对象转化成xml格式
程序员文章站
2022-03-31 16:52:17
...
1.导入的包
jettison-1.0.1.jar
xpp3_min-1.1.4c.jar
xstream-1.3.1.jar
2.编写一个普通对象
3.转化
jettison-1.0.1.jar
xpp3_min-1.1.4c.jar
xstream-1.3.1.jar
2.编写一个普通对象
package com.data;
public class User {
int age ;
String name ;
String address;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
3.转化
package com.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.data.User;
import com.thoughtworks.xstream.XStream;
public class TestXstream {
public static void main(String[] args) throws FileNotFoundException
{
// 初始化BEAN对象
User user = new User();
user.setAge(100);
user.setName("西门庆,庆哥");
user.setAddress("北京");
// 初始化XStream对象
XStream xStream = new XStream();
xStream.alias("User", User.class);//定义类别名
xStream.omitField(User.class, "name"); //定义某一个属性的值不进行xml序列化。
xStream.useAttributeFor(String.class); // 对所有String类型的字段定义为属性tag显示
xStream.useAttributeFor("address",String.class);// 对所有String类型的字段名定义为属性tag显示,读取的时候获取不了该值
FileOutputStream fs = new FileOutputStream("user.xml");
xStream.toXML(user, fs);
}
}
下一篇: Redis简述