前端之家收集整理的这篇文章主要介绍了
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.f2er.com/xml/298333.html