xstream如何将java对象转化成有cdata的xml
展开全部
实体类要加注解
实体类要加注解
@XStreamAlias("msg")
public class Msg implements Serializable {
private static final long serialVersionUID = 3196422897798539811L;
@XStreamAsAttribute
private String toUid;
@XStreamAsAttribute
private String fromUid;
@XStreamAsAttribute
private String flag;
@XStreamAsAttribute
private String time;
@XStreamAlias("content")
private String content;
@XStreamAlias("user")
private String user;
//省略geter、seter
}
然后写个工具类
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class SerializeXmlUtil {
/**
* java对象转化成xml字符串
* @param obj java对象实例
* @return String xml字符串
*/
public static String serializeToXml(Object obj) {
//XStream xstream = new XStream();
//直接用jaxp dom来解释
//XStream xstream=new XStream(new DomDriver());
//指定编码解析器,直接用jaxp dom来解释
XStream xstream=new XStream(new DomDriver("utf-8"));
//如果没有这句,xml中的根元素会是<包.类名>
//或者说:注解根本就没生效,所以的元素名就是类的属性
xstream.processAnnotations(obj.getClass());
StringBuffer xmlstrbuf = new StringBuffer();
xmlstrbuf.append("<?xml version=\"1.0\"?>");
xmlstrbuf.append("\r\n");
xmlstrbuf.append(xstream.toXML(obj));
return xmlstrbuf.toString();
}
/**
* 将传入xml字符串转化为java对象
* @param xmlstr
* @param cls xml对应的class类
* @return T xml对应的class类的实例对象
* 调用的方法实例:PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class);
*/
public static <T> T deSerizalizeFromXml(String xmlstr, Class<T> cls) throws Exception {
//注意:不是new Xstream();否则报错:java.lang.NoClassDefFoundError:
//org/xmlpull/v1/XmlPullParserFactory
XStream xstream = new XStream(new DomDriver());
xstream.processAnnotations(cls);
T obj = (T) xstream.fromXML(xmlstr);
return obj;
}
}
2014-01-16
展开全部
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings("unchecked")
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
});
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2014-01-16
展开全部
网上很多。百度。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询