原文: https://howtodoinjava.com/jaxb/xmlelementwrapper-annotation/

JAXB @XmlElementWrapper注解的 Java 示例及其在编组编组操作期间的用法详细说明。

1. @XmlElementWrapper类型

  1. 该注解生成围绕 XML 表示的包装器元素。
  2. 它主要用于在集合周围产生包装 XML 元素。
  3. 该注解可以与以下注解一起使用:XmlElementXmlElementsXmlElementRefXmlElementRefsXmlJavaTypeAdapter
  4. @XmlElementWrapper注解可以与以下程序元素一起使用:

    • JavaBean 属性
    • 非静态,非瞬态字段

2. JAXB @XmlElementWrapper示例

现在来看几个有关如何将@XmlElementWrapper@XmlElement一起使用来更改 XML 表示形式的示例。

2.1 使用@XmlElementWrapper@XmlElement(包装的集合)

  1. @XmlRootElement(name = "employee")
  2. @XmlAccessorType(XmlAccessType.FIELD)
  3. public class Employee implements Serializable {
  4. private static final long serialVersionUID = 1L;
  5. @XmlElementWrapper(name="hobbies")
  6. @XmlElement(name="hobby")
  7. private List<String> hobbies;
  8. private Integer id;
  9. private String firstName;
  10. private String lastName;
  11. }

以上转换为:

  1. <employee>
  2. <id>1</id>
  3. <firstName>Lokesh</firstName>
  4. <lastName>Gupta</lastName>
  5. <hobbies>
  6. <hobby>Swimming</hobby>
  7. <hobby>Playing</hobby>
  8. <hobby>Karate</hobby>
  9. </hobbies>
  10. </employee>

2.2 仅使用@XmlElementWrapper

  1. @XmlRootElement(name = "employee")
  2. @XmlAccessorType(XmlAccessType.FIELD)
  3. public class Employee implements Serializable {
  4. private static final long serialVersionUID = 1L;
  5. @XmlElementWrapper(name="hobbies")
  6. //@XmlElement(name="hobby") //Comment it out
  7. private List<String> hobbies;
  8. private Integer id;
  9. private String firstName;
  10. private String lastName;
  11. }

以上转换为:

  1. <employee>
  2. <id>1</id>
  3. <firstName>Lokesh</firstName>
  4. <lastName>Gupta</lastName>
  5. <hobbies>
  6. <hobbies>Swimming</hobbies>
  7. <hobbies>Playing</hobbies>
  8. <hobbies>Karate</hobbies>
  9. </hobbies>
  10. </employee>

2.3 不使用@XmlElementWrapper(未包装的集合)

  1. @XmlRootElement(name = "employee")
  2. @XmlAccessorType(XmlAccessType.FIELD)
  3. public class Employee implements Serializable {
  4. private static final long serialVersionUID = 1L;
  5. //@XmlElementWrapper(name="hobbies") //Comment it out
  6. @XmlElement(name="hobby")
  7. private List<String> hobbies;
  8. private Integer id;
  9. private String firstName;
  10. private String lastName;
  11. }

以上转换为:

  1. <employee>
  2. <id>1</id>
  3. <firstName>Lokesh</firstName>
  4. <lastName>Gupta</lastName>
  5. <hobby>Swimming</hobby>
  6. <hobby>Playing</hobby>
  7. <hobby>Karate</hobby>
  8. </employee>>

将我的问题放在评论部分。

学习愉快!

参考: XmlElementWrapper Java 文档