/**
* Xml和Bean互转工具类
* @author Alex
* @date 2022/06/02
*/
public class XMLUtil {
/**
* 将对象转换成String类型的xml
* @param obj 需要转换的对象
* @return XML格式的字符串
*/
public static String convertBeanToXml(Object obj) {
StringWriter result = new StringWriter();
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(obj, result);
result.close();
} catch (JAXBException | IOException e) {
e.printStackTrace();
}
return result.toString();
}
/**
* 讲对象转换成xml文件
* @param obj 需要转换的对象
* @param path 输出文件路径
*/
public static void convertBeanToXml(Object obj, String path) {
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
FileWriter fw = new FileWriter(path);
marshaller.marshal(obj, fw);
fw.flush();
fw.close();
} catch (JAXBException | IOException e) {
e.printStackTrace();
}
}
/**
* 将xml字符串转换成对象
* @param c 需要转换成的对象
* @param xmlStr 需要转换的xml字符串
* @return 转换后的对象
*/
@SuppressWarnings("unchecked")
public static <T> T convertXmlStrToObject(Class<T> c, String xmlStr) {
T t = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader sr = new StringReader(xmlStr);
t = (T) unmarshaller.unmarshal(sr);
sr.close();
} catch (JAXBException e) {
e.printStackTrace();
}
return t;
}
/**
* 将xml文件转换成对象
* @param c 需要转换成的对象
* @param xmlPath 需要转换的xml文件路径
* @return 转换后的对象
*/
@SuppressWarnings("unchecked")
public static <T> T convertXmlFileToObject(Class<T> c, String xmlPath) {
T t = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
FileReader fr = new FileReader(xmlPath);
t = (T) unmarshaller.unmarshal(fr);
fr.close();
} catch (JAXBException | IOException e) {
e.printStackTrace();
}
return t;
}
}
Xml和Bean互转工具类
最新推荐文章于 2023-07-25 21:24:54 发布