Features
- 将 Object 转换为 xml 格式字符串
- 将 xml 格式的 String 字符串转换为 Object
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class XMLUtil {
public static String toXmlString(Object obj) {
String result;
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Class<T> claaz) {
Object result;
try {
JAXBContext context = JAXBContext.newInstance(claaz);
Unmarshaller unmarshaller = context.createUnmarshaller();
result = unmarshaller.unmarshal(new StringReader(input));
} catch (Exception e) {
throw new RuntimeException(e);
}
return (T) result;
}
}