@XmlElementWrapper

在JAXB标准中,@XmlElementWrapper注解表示生成一个包装器元素。该注释支持两种形式的序列化。


    注意: @XmlElementWrapper仅允许出现在集合属性上。


第一步:定义将要转化的Java对象

    注@XmlElementWrapper_第1张图片

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 + "]";
	}
}

第二步: 生成xml文件并写入文件

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:



    25
    
        name-a
        name-b
        name-c
    


 这个示范代码生成的xml同时写入了文件和标准输出(控制台):

@XmlElementWrapper_第2张图片

@XmlElementWrapper_第3张图片



你可能感兴趣的:(JAXB,xml,object)