企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# JAXB `@XmlElementWrapper`注解示例 > 原文: [https://howtodoinjava.com/jaxb/xmlelementwrapper-annotation/](https://howtodoinjava.com/jaxb/xmlelementwrapper-annotation/) **JAXB `@XmlElementWrapper`注解**的 Java 示例及其在[编组](https://howtodoinjava.com/jaxb/marshaller-example/)和[编组](https://howtodoinjava.com/jaxb/jaxb-unmarshaller-example/)操作期间的用法详细说明。 ## 1\. `@XmlElementWrapper`类型 1. 该注解生成围绕 XML 表示的包装器元素。 2. 它主要用于在集合周围产生包装 XML 元素。 3. 该注解可以与以下注解一起使用:`XmlElement`,`XmlElements`,`XmlElementRef`,`XmlElementRefs`,`XmlJavaTypeAdapter`。 4. `@XmlElementWrapper`注解可以与以下程序元素一起使用: * JavaBean 属性 * 非静态,非瞬态字段 ## 2\. JAXB `@XmlElementWrapper`示例 现在来看几个有关如何将`@XmlElementWrapper`与`@XmlElement`一起使用来更改 XML 表示形式的示例。 #### 2.1 使用`@XmlElementWrapper`和`@XmlElement`(包装的集合) ```java @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; } ``` 以上转换为: ```java <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` ```java @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 out private List<String> hobbies; private Integer id; private String firstName; private String lastName; } ``` 以上转换为: ```java <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`(未包装的集合) ```java @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; } ``` 以上转换为: ```java <employee> <id>1</id> <firstName>Lokesh</firstName> <lastName>Gupta</lastName> <hobby>Swimming</hobby> <hobby>Playing</hobby> <hobby>Karate</hobby> </employee>> ``` 将我的问题放在评论部分。 学习愉快! 参考: [`XmlElementWrapper` Java 文档](https://docs.oracle.com/javase/7/docs/api/javax/xml/bind/annotation/XmlElementWrapper.html)