我使用XStream
将实体映射到xml String
@XStreamAlias("user")
public class User {
private String name;
private Integer age;
private String address;
private String gender;
...getter()/setter()...
}
我使用的util方法:
public static String getXmlFromEntity(Object obj, Class rootClazz, String rootAlias){
XStream magicApi = new XStream(new XppDriver(new NoNameCoder()));
magicApi.registerConverter(new MapEntryConverter());
magicApi.alias(rootAlias, rootClazz);
magicApi.autodetectAnnotations(Boolean.TRUE);
String xml = magicApi.toXML(obj);
return xml;
}
转换器
public static class MapEntryConverter implements Converter {
public boolean canConvert(Class clazz) {
return AbstractMap.class.isAssignableFrom(clazz);
}
public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {
AbstractMap map = (AbstractMap) value;
for (Object obj : map.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
writer.startNode(entry.getKey().toString());
Object val = entry.getValue();
if ( null != val ) {
writer.setValue(val.toString());
}else {
writer.setValue("bbb");
}
writer.endNode();
}
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Map<String, String> map = new HashMap<String, String>();
while(reader.hasMoreChildren()) {
reader.moveDown();
String key = reader.getNodeName(); // nodeName aka element's name
String value = reader.getValue();
map.put(key, value);
reader.moveUp();
}
return map;
}
}
我想得到一个结果,例如,如果未设置性别,那么Tag也应该作为空标记包含在内而不是在结果xml字符串中省略它:
<user>
<name>Tom</name>
<address>228 Park Ave S. New York, NY 10003</address>
</user>
我希望结果是:
<user>
<name>Tom</name>
<address>228 Park Ave S. New York, NY 10003</address>
<gender></gender>
<age></age>
</user>
我怎么能这样做?