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;
	}

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念