1. 创建出地图的转换器,然后使用反射转换器对物体进行清点:
static class MyConverter implements Converter {
private final Map<String, String> attributes;
private final Class<?> clazz;
private final Mapper mapper;
private final ReflectionProvider reflectionProvider;
public MyConverter(Mapper mapper,
ReflectionProvider reflectionProvider, Class<?> clazz,
Map<String, String> attributes) {
super();
this.mapper = mapper;
this.reflectionProvider = reflectionProvider;
this.attributes = attributes;
this.clazz = clazz;
}
@Override
public boolean canConvert(Class cls) {
return cls == clazz;
}
@Override
public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
for (String key : attributes.keySet()) {
writer.addAttribute(key, attributes.get(key));
}
Converter converter = new ReflectionConverter(mapper,
reflectionProvider);
context.convertAnother(p, converter);
}
@Override
public Object unmarshal(HierarchicalStreamReader arg0,
UnmarshallingContext arg1) {
// TODO Auto-generated method stub
return null;
}
}
摘自您的XStream 案的“地图片”和“反射”事例,并登记一个拥有一切必要装置的转换器:
XStream xs = new XStream(new DomDriver());
Mapper mapper = xs.getMapper();
ReflectionProvider reflectionProvider = xs.getReflectionProvider();
xs.alias("youralias", YourRoot.class);
xs.registerConverter(new MyConverter(mapper, reflectionProvider,
YourRoot.class, map));
System.out.println(xs.toXML(yourRoot));