java实体转换xml跟 xml转换java实体
public static T parseXML(Class clazz, String context) {
T result = null;
Locale.setDefault(Locale.ENGLISH);
try {
StringReader reader = new StringReader(context);
JAXBContext jc = JAXBContext.newInstance(clazz);
Unmarshaller u = jc.createUnmarshaller();
result = (T) u.unmarshal(reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String convertObjectToXml(String xmlEncoding, Object obj, Class> clazz) {
JAXBContext jaxbContext = null;
StringWriter outPutSW = new StringWriter();
try {
jaxbContext = JAXBContext.newInstance(clazz);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
if (!"UTF-8".equals(xmlEncoding))
jaxbMarshaller.setProperty("jaxb.encoding", xmlEncoding);
jaxbMarshaller.marshal(obj, outPutSW);
return outPutSW.toString();
} catch (JAXBException e) {
e.printStackTrace();
}
return "";
}