xml转化为对象,对象转化为xml
package com.picc.agricultural.util;
import com.picc.agricultural.pojo.BasePart;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;
public class XmlObject {
/**
* xml转化为对象
* @param clazz
* @param xmlStr
* @return
*/
public static Object xmlToObject(Class<?> clazz,String xmlStr){
Object xmlObject = null;
Reader reader = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
// xml转为对象的接口 反序列化
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
reader = new StringReader(xmlStr);
xmlObject = unmarshaller.unmarshal(reader);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null ) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return xmlObject;
}
public static String ObjectToXml(Class<?> clazz,Object ObjectXml){
String xmlStr = null;
Writer writer = new StringWriter();
try {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
// xml转为对象的接口 序列化
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(ObjectXml, writer);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null ) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return writer.toString();
}
}
备注:需要在转化的根实体类上面添加@XmlRootElement注解