微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jaxb 简单的对象与xml相互转换

/**
 * 
 */

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.io.FileUtils;

/**
 * 
 * @author zhangdapeng
 * @version 1.0,2014年7月18日
 * @since 1.0
 */
public class JaxbUtil {

	/**
	 * 
	 * @param obj
	 * @param encoding
	 * @return
	 * @throws JAXBException
	 */
	public static String convertObjectToXml(Object obj,String encoding) throws JAXBException {
		String result = null;
		JAXBContext context = JAXBContext.newInstance(obj.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
		marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding);

		StringWriter writer = new StringWriter();
		marshaller.marshal(obj,writer);
		result = writer.toString();

		return result;
	}

	/**
	 * 
	 * @param xml
	 * @param c
	 * @return
	 * @throws JAXBException 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T convertXmlToObject(String xml,Class<T> c) throws JAXBException {
		T t = null;
		JAXBContext context = JAXBContext.newInstance(c);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		StringReader sr = new StringReader(xml);
		//
		// int i;
		// do {
		// i = sr.read();
		// char c1 = (char) i;
		// System.out.print(c1);
		// } while (i != -1);

		t = (T) unmarshaller.unmarshal(sr);
		return t;
	}

	public static void main(String[] args) throws IOException,JAXBException {
		ThreadConfiguration test = new ThreadConfiguration();
		test.setCore(10);
		String c = JaxbUtil.convertObjectToXml(test,"utf-8");
		System.out.println(c);

		File file = new File("E:/workspace/testgs-maven/src/main/java/thread.xml");
		String xmlStr = FileUtils.readFiletoString(file,"UTF-8");

		test = JaxbUtil.convertXmlToObject(xmlStr,ThreadConfiguration.class);
		System.out.println(test.getKeepAliveTime());
	}
}

原文地址:https://www.jb51.cc/xml/298333.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。