XML与Object之间的互转
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML与Object之间的互转相关的知识,希望对你有一定的参考价值。
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)));
}
以上是关于XML与Object之间的互转的主要内容,如果未能解决你的问题,请参考以下文章