转自http://cai555.iteye.com/blog/464055
这几天在用xstream做转换的时候发现了类型不匹配的属性xStream会自动在节点加上class=xxxx,看着非常不爽
解决办法:
public class XMLUtil
{
private static final XStream xStream = new XStream();
// 将对象转为XML字符串
public static <T> String toXML(T obj)
{
Class<?> cls = obj.getClass();
xStream.alias(cls.getSimpleName().toLowerCase(), cls);
xStream.aliasSystemAttribute(null, "class"); // 去掉 class 属性
return xStream.toXML(obj);
}
// 将XML字符串转为对象
@SuppressWarnings({"unchecked"})
public static <T> T fromXML(String xml)
{
return (T) xStream.fromXML(xml);
}
}
public class XMLUtil
{
private static final XStream xStream = new XStream();
// 将对象转为XML字符串
public static <T> String toXML(T obj)
{
Class<?> cls = obj.getClass();
xStream.alias(cls.getSimpleName().toLowerCase(), cls);
xStream.aliasSystemAttribute(null, "class"); // 去掉 class 属性
return xStream.toXML(obj);
}
// 将XML字符串转为对象
@SuppressWarnings({"unchecked"})
public static <T> T fromXML(String xml)
{
return (T) xStream.fromXML(xml);
}
}