对象转xml
/**
* 将指定对象转换为xml字符串
*
* @param object
* @return
* @throws JAXBException
*/
public static String objectToXmlStr(Object object) throws JAXBException {
String xmlObj = "";
//1、调用JAXBContext,获取上下文对象
JAXBContext context = JAXBContext.newInstance(object.getClass());
//2、根据上下文获取marshaller对象
Marshaller m = context.createMarshaller();
//3、设置编码字符集,一般设置UTF-8
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//4、格式化XML输出,有分行和缩进
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//5、调用Marshaller类的marshal方法,编排内容到输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
m.marshal(object, baos);
//6、将输出流生成XML字符串
xmlObj = new String(baos.toByteArray());
return xmlObj.trim();
}
xml转对象
/**
* 将String类型的xml转换成对象
*
* @param clazz
* @param xmlStr
* @return
*/
public static Object xmlStrToObject(Class clazz, String xmlStr) {
Object xmlObject = null;
try {
xmlObject= clazz.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//1、调用JAXBContext,获取上下文对象
JAXBContext context = JAXBContext.newInstance(clazz.getClass());
//2、调用JAXBContext类的createUnmarshaller方法,创建反编排器
Unmarshaller u = context.createUnmarshaller();
//3、将xml字符串进行反编排
xmlObject = u.unmarshal(new StringReader(xmlStr));
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return xmlObject;
}
网友评论