原文: https://howtodoinjava.com/jaxb/xmlelementwrapper-annotation/
JAXB @XmlElementWrapper注解的 Java 示例及其在编组和编组操作期间的用法详细说明。
1. @XmlElementWrapper类型
- 该注解生成围绕 XML 表示的包装器元素。
- 它主要用于在集合周围产生包装 XML 元素。
- 该注解可以与以下注解一起使用:
XmlElement,XmlElements,XmlElementRef,XmlElementRefs,XmlJavaTypeAdapter。 @XmlElementWrapper注解可以与以下程序元素一起使用:- JavaBean 属性
- 非静态,非瞬态字段
2. JAXB @XmlElementWrapper示例
现在来看几个有关如何将@XmlElementWrapper与@XmlElement一起使用来更改 XML 表示形式的示例。
2.1 使用@XmlElementWrapper和@XmlElement(包装的集合)
@XmlRootElement(name = "employee")@XmlAccessorType(XmlAccessType.FIELD)public class Employee implements Serializable {private static final long serialVersionUID = 1L;@XmlElementWrapper(name="hobbies")@XmlElement(name="hobby")private List<String> hobbies;private Integer id;private String firstName;private String lastName;}
以上转换为:
<employee><id>1</id><firstName>Lokesh</firstName><lastName>Gupta</lastName><hobbies><hobby>Swimming</hobby><hobby>Playing</hobby><hobby>Karate</hobby></hobbies></employee>
2.2 仅使用@XmlElementWrapper
@XmlRootElement(name = "employee")@XmlAccessorType(XmlAccessType.FIELD)public class Employee implements Serializable {private static final long serialVersionUID = 1L;@XmlElementWrapper(name="hobbies")//@XmlElement(name="hobby") //Comment it outprivate List<String> hobbies;private Integer id;private String firstName;private String lastName;}
以上转换为:
<employee><id>1</id><firstName>Lokesh</firstName><lastName>Gupta</lastName><hobbies><hobbies>Swimming</hobbies><hobbies>Playing</hobbies><hobbies>Karate</hobbies></hobbies></employee>
2.3 不使用@XmlElementWrapper(未包装的集合)
@XmlRootElement(name = "employee")@XmlAccessorType(XmlAccessType.FIELD)public class Employee implements Serializable {private static final long serialVersionUID = 1L;//@XmlElementWrapper(name="hobbies") //Comment it out@XmlElement(name="hobby")private List<String> hobbies;private Integer id;private String firstName;private String lastName;}
以上转换为:
<employee><id>1</id><firstName>Lokesh</firstName><lastName>Gupta</lastName><hobby>Swimming</hobby><hobby>Playing</hobby><hobby>Karate</hobby></employee>>
将我的问题放在评论部分。
学习愉快!
