package com.ard.work.sdk.zlxd.utils;
|
|
import javax.xml.bind.JAXBContext;
|
import javax.xml.bind.Marshaller;
|
import javax.xml.bind.Unmarshaller;
|
import java.io.StringReader;
|
import java.io.StringWriter;
|
|
public class XmlUtils {
|
|
/**
|
* 将对象转换为 XML 字符串
|
*/
|
public static String toXml(Object obj) throws Exception {
|
JAXBContext context = JAXBContext.newInstance(obj.getClass());
|
Marshaller marshaller = context.createMarshaller();
|
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
|
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
|
StringWriter writer = new StringWriter();
|
marshaller.marshal(obj, writer);
|
return writer.toString();
|
}
|
|
/**
|
* 将 XML 字符串转换为对象
|
*/
|
public static <T> T fromXml(String xml, Class<T> clazz){
|
try {
|
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
|
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
|
return (T) unmarshaller.unmarshal(new StringReader(xml));
|
} catch (Exception e) {
|
throw new RuntimeException("XML反序列化失败", e);
|
}
|
}
|
}
|