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 轉換後的對象br/>*/
@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)));
}