今天开发接口,遇到xml的格式比较特别大概格式为
<DBSET>
<R>
<C N="RECORD_ID">111111</C>
<C N="ORG_NO">2222</C>
</R>
<R>
<C N="RECORD_ID">333</C>
<C N="ORG_NO">4444</C>
</R>
</DBSET>
目前解决思路就是将R
看做Map
, C
看做一个键值对。
<R>
<C N="RECORD_ID">111111</C>
<C N="ORG_NO">2222</C>
</R>
理解为
{
RECORD_ID: 111111,
ORG_NO: 2222
}
定义一个JavaBean用来描述<R/>
@XStreamAlias("R")
@XStreamConverter(ResultConverter.class)
public class Result {
public Map<String, Object> result = new HashMap<String, Object>();
public void put(String key, Object val){
result.put(key, val);
}
public void putAll(Map<String,Object> map) {
result.putAll(map);
}
public Object get(String key) {
return result.get(key);
}
}
Converter
类
public class ResultConverter implements Converter {
@Override
public boolean canConvert(Class class_) {
return "com.zhbr.ws.inf.yx.ws.entity.yxhc2.Result".equals(class_.getName());
}
@Override
public void marshal(Object source, HierarchicalStreamWriter writer,
MarshallingContext context) {
Result r = (Result) source;
Map<String,Object> result = r.result;
if(result.isEmpty()) return;
for(Entry<String,Object> entry: result.entrySet()){
writer.startNode("C");
writer.addAttribute("N", entry.getKey());
writer.setValue( StrUtil.toStr(entry.getValue()));
writer.endNode();
}
}
@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
Result r = new Result();
while (reader.hasMoreChildren()) {
reader.moveDown();
if ("C".equals(reader.getNodeName())) {
String col = reader.getAttribute("N");
String val = reader.getValue();
r.put(col, val);
}
reader.moveUp();
}
return r;
}
}
测试
Result r = new Result();
r.put("RETURN_MSG", "xxx");
r.put("RETURN_FLAG", "0");
String xml = XmlUtil.toXml(r);
System.out.println(xml);
Result r2 = XmlUtil.toBean(xml, Result.class);
System.out.println(r2);
输出
<R>
<C N="RETURN_MSG">xxx</C>
<C N="RETURN_FLAG">0</C>
</R>
RETURN_MSG: xxx,RETURN_FLAG: 0