/**
* @Description:
*
* @Title: JAXBUtil.java
* @Package com.joyce.util
* @Copyright: Copyright (c) 2014
*
* @author Comsys-LZP
* @date 2014-6-10 下午02:54:40
* @version V2.0
*/
package com.joyce.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
* @Description:JAXB对象和XML转换util
*
* @ClassName: JAXBUtil
* @Copyright: Copyright (c) 2014
*
* @author Comsys-LZP
* @date 2014-6-10 下午02:54:40
* @version V2.0
*/
public class JAXBUtil {
/**
* @Description: 将对象转换为XML
*
* @param obj
* @param beanClass
* @return
* @throws Exception
*
* @Title: JAXBUtil.java
* @Copyright: Copyright (c) 2014
*
* @author Comsys-LZP
* @date 2014-6-10 下午04:23:45
* @version V2.0
*/
@SuppressWarnings("unchecked")
public String objectToXmlStr(Object obj, Class beanClass) throws Exception {
JAXBContext context = JAXBContext.newInstance(beanClass);
// 根据上下文获取marshaller对象
Marshaller marshaller = context.createMarshaller();
// 设置编码字符集
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
// 格式化XML输出,有分行和缩进
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// 打印到控制台
marshaller.marshal(obj, System.out);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
marshaller.marshal(obj, baos);
String xmlObj = new String(baos.toByteArray());
return xmlObj.replace(" standalone=\"yes\"", "");
}
/**
* @Description: 将对象转换为XML并且写入文件
*
* @param obj
* @param beanClass
* @param file
* @throws Exception
*
* @Title: JAXBUtil.java
* @Copyright: Copyright (c) 2014
*
* @author Comsys-LZP
* @date 2014-6-10 下午04:24:13
* @version V2.0
*/
@SuppressWarnings("unchecked")
public void objectToXmlStr(Object obj, Class beanClass, File file) throws Exception {
JAXBContext context = JAXBContext.newInstance(beanClass);
// 根据上下文获取marshaller对象
Marshaller marshaller = context.createMarshaller();
// 设置编码字符集
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
// 格式化XML输出,有分行和缩进
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// 打印到控制台
marshaller.marshal(obj, System.out);
marshaller.marshal(obj, file);
}
/**
* @Description: XML转换为对象
*
* @param <T>
* @param file
* @param beanClass
* @return
* @throws Exception
*
* @Title: JAXBUtil.java
* @Copyright: Copyright (c) 2014
*
* @author Comsys-LZP
* @date 2014-6-10 下午04:24:50
* @version V2.0
*/
@SuppressWarnings("unchecked")
public <T> T xmlStrToObject(File file, Class<T> beanClass) throws Exception {
T bean = beanClass.newInstance();
JAXBContext context = JAXBContext.newInstance(beanClass);
Unmarshaller unmarshaller = context.createUnmarshaller();
bean = (T) unmarshaller.unmarshal(file);
return bean;
}
}
- 1
- 2
- 3
前往页