在JAXB标准中,@XmlElementWrapper注解表示生成一个包装器元素。该注释支持两种形式的序列化。
注意: @XmlElementWrapper仅允许出现在集合属性上。
第一步:定义将要转化的Java对象
注
package jijian.test; 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 jijian.test; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class Object2XmlDemo { public static void main(String[] args) throws JAXBException { Customer customer = new Customer(); customer.setId(100); customer.setNames(new String[]{"name-a","name-b","name-c"}); customer.setAge(25); File file = new File("D:\\file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); jaxbMarshaller.marshal(customer,file); jaxbMarshaller.marshal(customer,System.out); } }
生成的xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customer id="100"> <age>25</age> <allnames> <myname>name-a</myname> <myname>name-b</myname> <myname>name-c</myname> </allnames> </customer>
这个示范代码生成的xml同时写入了文件和标准输出(控制台):
原文链接:https://www.f2er.com/xml/297372.html