Java中Xml和实体互转

心已赠人 2024-03-23 15:41 124阅读 0赞

文章目录

  • Java中Xml和实体互转
      1. 工具类 JaxbUtil
      1. 实体转Xml演示
      • 2-1 实体类,Main方法中,含实体和Xml互转的测试代码
      • 2-2 生成的Xml结果
      1. [Java中操作Xml,可参考我写的另一篇博客【更完整、使用推荐】](https://blog.csdn.net/qq\_17847881/article/details/130855130)

Java中Xml和实体互转

1. 工具类 JaxbUtil

  1. import java.io.StringReader;
  2. import java.io.StringWriter;
  3. import java.util.Collection;
  4. import java.util.concurrent.ConcurrentHashMap;
  5. import java.util.concurrent.ConcurrentMap;
  6. import javax.xml.bind.JAXBContext;
  7. import javax.xml.bind.JAXBElement;
  8. import javax.xml.bind.JAXBException;
  9. import javax.xml.bind.Marshaller;
  10. import javax.xml.bind.Unmarshaller;
  11. import javax.xml.bind.annotation.XmlAnyElement;
  12. import javax.xml.namespace.QName;
  13. import org.apache.commons.lang3.StringUtils;
  14. import org.apache.commons.lang3.Validate;
  15. import sun.awt.geom.AreaOp;
  16. public class JaxbUtil {
  17. @SuppressWarnings("rawtypes")
  18. private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();
  19. /**
  20. * Java Object->Xml without encoding.
  21. */
  22. @SuppressWarnings("rawtypes")
  23. public static String toXml(Object root) {
  24. Class clazz = root.getClass();
  25. return toXml(root, clazz, null);
  26. }
  27. /**
  28. * Java Object->Xml with encoding.
  29. */
  30. @SuppressWarnings("rawtypes")
  31. public static String toXml(Object root, String encoding) {
  32. Class clazz = root.getClass();
  33. return toXml(root, clazz, encoding);
  34. }
  35. /**
  36. * Java Object->Xml with encoding.
  37. */
  38. @SuppressWarnings("rawtypes")
  39. public static String toXml(Object root, Class clazz, String encoding) {
  40. try {
  41. StringWriter writer = new StringWriter();
  42. createMarshaller(clazz, encoding).marshal(root, writer);
  43. return writer.toString();
  44. } catch (JAXBException e) {
  45. e.printStackTrace();
  46. }
  47. return null;
  48. }
  49. /**
  50. * Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
  51. */
  52. @SuppressWarnings("rawtypes")
  53. public static String toXml(Collection<?> root, String rootName, Class clazz) {
  54. return toXml(root, rootName, clazz, null);
  55. }
  56. /**
  57. * Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
  58. */
  59. @SuppressWarnings("rawtypes")
  60. public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
  61. try {
  62. CollectionWrapper wrapper = new CollectionWrapper();
  63. wrapper.collection = root;
  64. JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
  65. CollectionWrapper.class, wrapper);
  66. StringWriter writer = new StringWriter();
  67. createMarshaller(clazz, encoding).marshal(wrapperElement, writer);
  68. return writer.toString();
  69. } catch (JAXBException e) {
  70. e.printStackTrace();
  71. }
  72. return null;
  73. }
  74. /**
  75. * Xml->Java Object.
  76. */
  77. @SuppressWarnings("unchecked")
  78. public static <T> T fromXml(String xml, Class<T> clazz) {
  79. try {
  80. StringReader reader = new StringReader(xml);
  81. return (T) createUnmarshaller(clazz).unmarshal(reader);
  82. } catch (JAXBException e) {
  83. e.printStackTrace();
  84. }
  85. return null;
  86. }
  87. /**
  88. * 创建Marshaller并设定encoding(可为null).
  89. * 线程不安全,需要每次创建或pooling。
  90. */
  91. @SuppressWarnings("rawtypes")
  92. public static Marshaller createMarshaller(Class clazz, String encoding) {
  93. try {
  94. JAXBContext jaxbContext = getJaxbContext(clazz);
  95. Marshaller marshaller = jaxbContext.createMarshaller();
  96. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  97. if (StringUtils.isNotBlank(encoding)) {
  98. marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
  99. }
  100. return marshaller;
  101. } catch (JAXBException e) {
  102. e.printStackTrace();
  103. }
  104. return null;
  105. }
  106. /**
  107. * 创建UnMarshaller.
  108. * 线程不安全,需要每次创建或pooling。
  109. */
  110. @SuppressWarnings("rawtypes")
  111. public static Unmarshaller createUnmarshaller(Class clazz) {
  112. try {
  113. JAXBContext jaxbContext = getJaxbContext(clazz);
  114. return jaxbContext.createUnmarshaller();
  115. } catch (JAXBException e) {
  116. e.printStackTrace();
  117. }
  118. return null;
  119. }
  120. @SuppressWarnings("rawtypes")
  121. protected static JAXBContext getJaxbContext(Class clazz) {
  122. Validate.notNull(clazz, "'clazz' must not be null");
  123. JAXBContext jaxbContext = jaxbContexts.get(clazz);
  124. if (jaxbContext == null) {
  125. try {
  126. jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
  127. jaxbContexts.putIfAbsent(clazz, jaxbContext);
  128. } catch (JAXBException ex) {
  129. throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz + "]: "
  130. + ex.getMessage(), ex);
  131. }
  132. }
  133. return jaxbContext;
  134. }
  135. /**
  136. * 封装Root Element 是 Collection的情况.
  137. */
  138. public static class CollectionWrapper {
  139. @XmlAnyElement
  140. protected Collection<?> collection;
  141. }
  142. }

2. 实体转Xml演示

2-1 实体类,Main方法中,含实体和Xml互转的测试代码

  1. package com.ruoyi.system.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import java.io.Serializable;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import javax.xml.bind.annotation.XmlAccessType;
  7. import javax.xml.bind.annotation.XmlAccessorType;
  8. import javax.xml.bind.annotation.XmlElement;
  9. import javax.xml.bind.annotation.XmlRootElement;
  10. import javax.xml.bind.annotation.XmlTransient;
  11. //设置生成的xml的根节点的名称
  12. @XmlRootElement(name="sendHospitalInfo")
  13. //设置根据字段还是方法生成
  14. @XmlAccessorType(XmlAccessType.FIELD)
  15. public class Hospital implements Serializable {
  16. //xml节点的名称
  17. @XmlElement(name="hospitalId")
  18. private String hospitalid;
  19. //忽略此属性
  20. @XmlTransient
  21. private long id;
  22. @XmlElement(name="hospitalName")
  23. private String hospitalname;
  24. public String getHospitalid() {
  25. return hospitalid;
  26. }
  27. public void setHospitalid(String hospitalid) {
  28. this.hospitalid = hospitalid;
  29. }
  30. public long getId() {
  31. return id;
  32. }
  33. public void setId(long id) {
  34. this.id = id;
  35. }
  36. public String getHospitalname() {
  37. return hospitalname;
  38. }
  39. public void setHospitalname(String hospitalname) {
  40. this.hospitalname = hospitalname;
  41. }
  42. public static void main(String[] args) {
  43. Hospital sydw = new Hospital();
  44. sydw.setHospitalid("001");
  45. sydw.setHospitalname("hospital_name");
  46. Hospital sydw2 = new Hospital();
  47. sydw2.setHospitalid("002");
  48. sydw2.setHospitalname("hospital_name");
  49. List<Hospital> lists = new ArrayList<>();
  50. lists.add(sydw);
  51. lists.add(sydw2);
  52. Demo demo = new Demo();
  53. demo.setHospitals(lists);
  54. // 实体转xml
  55. System.out.println(JaxbUtil.toXml(demo));
  56. System.out.println(JaxbUtil.toXml(sydw));
  57. // xml 转实体
  58. Demo demo1 = new Demo();
  59. demo1=JaxbUtil.fromXml(JaxbUtil.toXml(demo),Demo.class);
  60. System.out.println(JSON.toJSONString(demo1));
  61. }
  62. }
  63. @XmlRootElement(name="sendHospitalInfoList")
  64. //设置根据字段还是方法生成
  65. @XmlAccessorType(XmlAccessType.FIELD)
  66. class Demo{
  67. private List<Hospital> hospitals;
  68. public List<Hospital> getHospitals() {
  69. return hospitals;
  70. }
  71. public void setHospitals(List<Hospital> hospitals) {
  72. this.hospitals = hospitals;
  73. }
  74. }

2-2 生成的Xml结果

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <sendHospitalInfoList>
  3. <hospitals>
  4. <hospitalId>001</hospitalId>
  5. <hospitalName>hospital_name</hospitalName>
  6. </hospitals>
  7. <hospitals>
  8. <hospitalId>002</hospitalId>
  9. <hospitalName>hospital_name</hospitalName>
  10. </hospitals>
  11. </sendHospitalInfoList>
  12. <!-- 对应的Json
  13. {"hospitals":[{"hospitalid":"001","hospitalname":"hospital_name","id":0},
  14. {"hospitalid":"002","hospitalname":"hospital_name","id":0}]}
  15. -->

3. Java中操作Xml,可参考我写的另一篇博客【更完整、使用推荐】

发表评论

表情:
评论列表 (有 0 条评论,124人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java Xml与对象的

    在java开发中我们经常会遇到Xml与对象互相转换的情况,尤其是针对WebService访问时会涉及到xml与对象的转换问题。目前可以用于xml与对象互转的方式有很多这里采用j