xStream javaBean转为xml时,怎么保留空节点
目前当javaBean中属性name没有值时,转为xml后就没有name这个节点了。我需要的是,即便属性name没有值,转换后的xml也保留name这个节点,如<name...
目前当javaBean中属性name没有值时 ,转为xml后就没有name这个节点了。
我需要的是,即便属性name没有值,转换后的xml也保留name这个节点,如<name/> 展开
我需要的是,即便属性name没有值,转换后的xml也保留name这个节点,如<name/> 展开
展开全部
使用一个自定义的Converter:
public class Student{
String name;
int age;
String teacher;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
.......
......//Like that mention other getter and setter method
}
public class StudentConverter implements Converter{
public boolean canConvert(Class clazz) {
return clazz.equals(Test.class);
}
public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
Student student = (Student ) value;
writer.startNode("name");
writer.setValue(test.getName());
writer.endNode();
writer.startNode("age");
writer.setValue(test.getAge());
writer.endNode();
writer.startNode("teacher");
String teacher = test.getTeacher();
if(teacher == null)
writer.setValue("");
else
writer.setValue(teacher);
writer.endNode();
}
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
Student student = new Student();
test.setName(reader.getNodeName());
test.setAge(reader.getNodeName());
test.setTeacher(reader.getNodeName());
return student;
}
}
public class App1{
public static void main(String args[]) {
XStream stream = new XStream(new StaxDriver());
Student st = new Student();
st.setName("ABC");
t.setAge(21);
stream.registerConverter(new StudentConverter());
stream.alias("student", Student.class);
System.out.println(stream.toXML(st));
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询