在JAXB标准中,@XmlElementWrapper注解表示生成一个包装 XML 表示形式的包装器元素。 此元素主要用于生成一个包装集合的包装器 XML 元素。因此,该注释支持以下两种形式的序列化。
注:@XmlElementWrapper仅允许出现在集合属性上。
第一步:定义将要转化的Java对象
package step1.wrapper;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String[] names;
int age;
int id;
//使用@XmlElementWrapper注解后,将会在原xml结点上再包装一层xml
@XmlElementWrapper(name="allnames")
@XmlElement(name="myname")
public String[] getNames() {
return names;
}
public void setNames(String[] names) {
this.names = names;
}
@XmlElement
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@XmlAttribute
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Customer [id=" + id + ",names=" + names + ",age=" + age + "]";
}
}
第二步:编组
package step1.wrapper;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
//Marshaller
public class Object2XmlDemo {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setNames(new String[]{"name-a","name-b","name-c"});
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
生成的xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customer id="100"> <age>29</age> <allnames> <myname>name-a</myname> <myname>name-b</myname> <myname>name-c</myname> </allnames> </customer>