private static final String W3C_XML_SCHEMA_NS_URI = "http://www.w3.org/2001/XMLSchema";
/** * 将对象转换成xml * * @param obj 要转成xml的对象 * @param xsdPath 标准的xml文件就传null * @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(); }
/**
* 将xml格式转换为对象.
*
* @param xml xml字符串
* @param clazz 要转换成的对象
* @param xsdPath 标准的xml解析传null
* @return 转换后的对象
*/
@SuppressWarnings("unchecked")
public static <T> T xmlToObj(String xml, Class<T> clazz, String xsdPath) throws JAXBException, SAXException {
JAXBContext jAXBContext = JAXBContext.newInstance(clazz);
Unmarshaller um = jAXBContext.createUnmarshaller();
if (TextUtils.isNotEmpty(xsdPath)) {
um.setSchema(SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI).newSchema(new File(xsdPath)));
}
return (T) um.unmarshal(new StreamSource(new StringReader(xml)));
}