1.xstream xml转bean对象,双划线问题
解决:主要是用到了new XmlFriendlyNameCoder("_-", "_"),在创建XStream对象时可XStream xStream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));
2.获取节点的属性值以及自身值
方法1:@XStreamConverter(value=ToAttributedValueConverter.class, strings={"value"})
对应的value是bean对象的属性名,具体示例:
@XStreamAlias("RETURNCODE") @XStreamConverter(value=ToAttributedValueConverter.class, strings={"value"}) public class ReturnCodeVO { @XStreamAsAttribute @XStreamAlias("CODE") private String code; @XStreamAsAttribute @XStreamAlias("MSG") private String msg; @XStreamAsAttribute @XStreamAlias("CMSG") private String cmsg; private String value; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getCmsg() { return cmsg; } public void setCmsg(String cmsg) { this.cmsg = cmsg; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
方法2:使用转换器Converter,具体示例如下:
public class CityConverter implements Converter { public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { City city = (City) value; writer.addAttribute("id", city.getId()); writer.addAttribute("type", city.getType().toString()); writer.setValue(city.getName()); } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { City city = new City(); city.setName(reader.getValue()); city.setId(reader.getAttribute("id")); city.setType(reader.getAttribute("type")); return city; } public boolean canConvert(Class clazz) { return clazz.equals(City.class); } }
调用XStream时进行设置:
XStream xStream = new XStream();
xStream.registerConverter(new CityConverter());
xStream.alias("loc", City.class);