架构师之xml----xml 和对象互转工具类

前端之家收集整理的这篇文章主要介绍了架构师之xml----xml 和对象互转工具类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1.前言。

如题

2。代码

  1. import javax.xml.bind.JAXBContext;
  2. import javax.xml.bind.JAXBException;
  3. import javax.xml.bind.Marshaller;
  4. import javax.xml.bind.Unmarshaller;
  5. /**
  6. * XML的帮助类
  7. *
  8. * @author wanganqi
  9. * @version v1.0
  10. * @since 2014年8月13日下午2:38:52
  11. */
  12. public class XmlHelper
  13. {
  14. /**
  15. * 将自定义数据对象转化为XML字符串
  16. *
  17. * @param clazz 自定义数据类型
  18. * @param object 自定义数据对象
  19. * @return XML字符串
  20. * @throws JAXBException 异常
  21. */
  22. public static String objectToXML(Class clazz,Object object)
  23. throws JAXBException
  24. {
  25. String xml = null;
  26. JAXBContext context = JAXBContext.newInstance(clazz);
  27. Marshaller m = context.createMarshaller();
  28. m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
  29. Writer w = new StringWriter();
  30. m.marshal(object,w);
  31. xml = w.toString();
  32. return xml;
  33. }
  34. /**
  35. * 将XML字符串转化为自定义数据对象
  36. *
  37. * @param clazz 自定义数据类型
  38. * @param xml XML字符串
  39. * @return 自定义数据对象
  40. * @throws JAXBException 异常
  41. */
  42. public static Object xmlToObject(Class clazz,String xml)
  43. throws JAXBException
  44. {
  45. JAXBContext context = JAXBContext.newInstance(clazz);
  46. Unmarshaller um = context.createUnmarshaller();
  47. return um.unmarshal(new StringReader(xml));
  48. }
  49. }
  50.  
转自:http://www.cnblogs.com/wgp13x/p/3995368.html

猜你在找的XML相关文章