package com.upyuns.platform.rs.universal.weixin.util;

import java.io.Writer;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppDriver;

/**
 * Xml工具类
 * 
 * @author Deacon
 * 
 */
public class XmlUtils {

	private static String PREFIX_CDATA = "<![CDATA[";
	private static String SUFFIX_CDATA = "]]>";

	public static XStream getXStream() 
	{
		return new XStream(new XppDriver(new XmlFriendlyReplacer("_-", "_") {
			public HierarchicalStreamWriter createWriter(Writer out) {
				return new PrettyPrintWriter(out) {
					// 对所有xml节点的转换都增加CDATA标记
					boolean cdata = true;

					@SuppressWarnings({ "rawtypes" })
					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);
						}
					}
				};
			}
		}));
	}

	public static String toXml(String alias, Class cls, Object obj) {
		XStream xstream = getXStream();
		xstream.alias(alias, cls);
		return xstream.toXML(obj);
	}

	public static <T> T fromXml(String alias, Class cls, String xml) {
		XStream xstream = getXStream();
		xstream.alias(alias, cls);
		return (T) xstream.fromXML(xml);
	}
	
}
