XML<-->Object 工具类

import org.apache.commons.lang.StringUtils;

import com.seeyon.v3x.bean.Person;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 将java对象序列化成xml,以及反序列化<br>
 * 
 * <pre>
 * e.g 
 * 序列化
 * UserMessage m = new UserMessage();
 * m.setter...
 * 
 * String xml = XMLCoder.encoder(m);
 * 
 * 反序列化
 * UserMessage msg = (UserMessage)XMLCoder.decoder(xml);
 * </pre>
 * 
 * @author <a href="mailto:[email protected]">Tanmf</a>
 * @version 1.0 2007-3-27
 */
public final class XMLCoder {
	// private static Log log = LogFactory.getLog(XMLCoder.class);

	/**
	 * 将java对象序列化成xml
	 * 
	 * @param o
	 *            要求该Class可以通过newInstance 方法创建一个类的实例
	 * @return xml字符串
	 */
	public static String encoder(Object o) {
		if (o == null) {
			return null;
		}

		XStream xstream = new XStream(new DomDriver());
		return xstream.toXML(o);
		/*
		 * 
		 * OutputStream out = null; try { out = new ByteArrayOutputStream();
		 * 
		 * XMLEncoder x = new XMLEncoder(out);
		 * 
		 * x.writeObject(o); x.close();
		 * 
		 * return out.toString(); } catch (Exception e) { log.error("将[" + o +
		 * "]序列化成xml", e); } finally { if (out != null) { try { out.close(); }
		 * catch (Exception e) { } } }
		 * 
		 * return null;
		 */
	}

	/**
	 * 将xml字符串反序列化成对象
	 * 
	 * @param xml
	 * @return
	 */
	public static Object decoder(String xml) {
		if (StringUtils.isBlank(xml)) {
			return null;
		}

		XStream xstream = new XStream(new DomDriver());
		return xstream.fromXML(xml);

		/*
		 * InputStream in = null; try { in = IOUtils.toInputStream(xml);
		 * XMLDecoder x = new XMLDecoder(in); Object o = x.readObject();
		 * x.close();
		 * 
		 * return o; } catch (Exception e) { log.error("将[" + xml + "]反序列化成对象",
		 * e); } finally { if (in != null) { try { in.close(); } catch
		 * (Exception e) { } } }
		 * 
		 * return null;
		 */
	}

	public static void main(String[] args) {
		XMLCoder xmlCoder = new XMLCoder();
		Person person = new Person("Lucas", "[email protected]");

		String xml_String = xmlCoder.encoder(person);
		System.out.println(xml_String);

		Person p = (Person) xmlCoder
				.decoder("<com.seeyon.v3x.bean.Person><name>Lucas</name><email>[email protected]</email></com.seeyon.v3x.bean.Person>");
	
		System.out.println(p.getEmail());
		System.out.println(p.getName());
	}

}
采用xstream解析xml对象,使用前需要加入相应的jar文件


你可能感兴趣的:(xml)