JAXB 操作XML 与 Object

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

Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。是一种xml与object映射绑定技术标准。

JDK5以下开发需要的jar包:activation.jar、jaxb-api.jar、 jaxb-impl.jar、 jsr173-api.jar

JDK6以上版本已经集成JAXB2的JAR,在目录{JDK_HOME}/jre/lib/rt.jar中。


@XmlAccessorType 注解 的枚举常量值说明:



代码片段:

  1. * xml字符串 pojo
  2. *
  3. * @param t
  4. * @param xmlStr
  5. * @return
  6. */
  7. @SuppressWarnings("rawtypes")
  8. public static Object jaxbReadXml(Class cls,String xmlStr) {
  9. ByteArrayInputStream stream = null;
  10. try {
  11. JAXBContext context = JAXBContext.newInstance(cls);
  12. stream = new ByteArrayInputStream(xmlStr.getBytes("utf-8"));
  13. Unmarshaller um = context.createUnmarshaller();
  14. return um.unmarshal(stream);
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. logger.error("----xml转对象出错:"+e.getMessage());
  18. } finally {
  19. if (stream != null) {
  20. try {
  21. stream.close();
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }
  27. return null;
  28. }
  29.  
  30. @SuppressWarnings("rawtypes")
  31. public static Object jaxbReadXml(Class cls,byte[] bs) {
  32. return jaxbReadXml(cls,new ByteArrayInputStream(bs));
  33. }
  34. @SuppressWarnings("rawtypes")
  35. public static Object jaxbReadXml(Class cls,InputStream in) {
  36. try {
  37. JAXBContext context = JAXBContext.newInstance(cls);
  38. Unmarshaller um = context.createUnmarshaller();
  39. return um.unmarshal(in);
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. } finally {
  43. if (in != null) {
  44. try {
  45. in.close();
  46. } catch (Exception e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. return null;
  52. }
  53.  
  54. /**
  55. * pojo 转 xml字符串
  56. *
  57. * @param pojo
  58. * @return
  59. */
  60. public static <T> String jaxbWriteXml(T pojo) {
  61. StringWriter out = null;
  62. String xmlStr = null;
  63. try {
  64. JAXBContext context = JAXBContext.newInstance(pojo.getClass());
  65. Marshaller marshaller = context.createMarshaller();
  66. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
  67. out = new StringWriter();
  68. marshaller.marshal(pojo,out);
  69. xmlStr = out.toString();
  70. // System.out.println(xmlStr);
  71. } catch (Exception e) {
  72. e.printStackTrace();
  73. logger.error("----对象转xml出错:"+e.getMessage());
  74. } finally {
  75. if (out != null) {
  76. try {
  77. out.close();
  78. } catch (IOException e) {
  79. e.printStackTrace();
  80. }
  81. }
  82. }
  83. return xmlStr;
  84. }

猜你在找的XML相关文章