使用此函数将Object转换为xml字符串(应称为convertToXml(sourceObject,Object.class);)->
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
public static <T> String convertToXml(T source, Class<T> clazz) throws JAXBException {
String result;
StringWriter sw = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
QName qName = new QName(StringUtils.uncapitalize(clazz.getSimpleName()));
JAXBElement<T> root = new JAXBElement<T>(qName, clazz, source);
jaxbMarshaller.marshal(root, sw);
result = sw.toString();
return result;
}
使用此函数将xml字符串转换为Object back->(应称为createObjectFromXmlString(xmlString, Object.class)
)
public static <T> T createObjectFromXmlString(String xml, Class<T> clazz) throws JAXBException, IOException{
T value = null;
StringReader reader = new StringReader(xml);
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<T> rootElement=jaxbUnmarshaller.unmarshal(new StreamSource(reader),clazz);
value = rootElement.getValue();
return value;
}
StringWriter
很老 在幕后,它使用StringBuffer
了本来可以使用更快的方法的方法,StringBuilder
但是当StringWriter首次制作时,这种方法就不存在了。因此,每次调用都sw.toString()
意味着同步。如果您正在寻找性能,那就不好了。