XML格式String 与 Object互换

前端之家收集整理的这篇文章主要介绍了XML格式String 与 Object互换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近项目用到xml格式的String类型与Object类型的相互转换,经过学习和前辈指点终于有所了解。在此写两个方法用户相互转换:

1、Object转化为xml格式String

public static String toXml(Object obj) {
		String xmlStr = null;
		JAXBContext jaxbContext = null;
		Marshaller marshaller = null;
		StringWriter writer = null;
		try {
			jaxbContext = JAXBContext.newInstance(obj.getClass());
			marshaller = jaxbContext.createMarshaller();
			writer = new StringWriter();
			marshaller.marshal(obj,writer);
			xmlStr = writer.toString();
		} catch (JAXBException e) {
			LOGGER.error("转换失败");
		}
		return xmlStr;
	}

2、xml格式String转化为Object
public static <T> T fromXml(String xmlStr,Class<T> _class) {
		T result = null;
		JAXBContext jaxbContext = null;
		try {
			StringReader reader = new StringReader(xmlStr);
			jaxbContext = JAXBContext.newInstance(_class);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			result = (T) jaxbUnmarshaller.unmarshal(reader);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
原文链接:https://www.f2er.com/xml/296892.html

猜你在找的XML相关文章