private static final String W3C_XML_SCHEMA_NS_URI = "http://www.w3.org/2001/XMLSchema";ide
/**xml
@return xml格式的字符串
*/
public static String objToXml(Object obj, String xsdPath) throws JAXBException, SAXException {
StringWriter sw = new StringWriter();
JAXBContext jAXBContext;
jAXBContext = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = jAXBContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK"); // 防止文件中文亂碼
if (TextUtils.isNotEmpty(xsdPath)) {
marshaller.setSchema(SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI).newSchema(new File(xsdPath)));
}
marshaller.marshal(obj, sw);
return sw.toString();
}對象
/**字符串