JAXB中各种常见注解小结

在JAXB中(用于JAVA对象和xml之间的转换),经常出现各类的 @XmlElement这样的标记,
下面就来以一个例子小结下,加深学习:


import java.util.*;
import javax.xml.bind.annotation.*;
 
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    private List<String> emailAddresses;
     
    public Customer() {
        emailAddresses = new ArrayList<String>();
    }
 
    public List<String> getEmailAddresses() {
        return emailAddresses;
    }
 
    public void setEmailAddresses(List<String> emailAddresses) {
        this.emailAddresses = emailAddresses;
    }
 
}



这个是一个典型的POJO了,其中引用了对象emailAddress,是一个List,那么下面演示各类用法:
  先看默认的调用代码如下:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Customer.class);
 
        Customer customer = new Customer();
        customer.getEmailAddresses().add("[email protected]");
        customer.getEmailAddresses().add("[email protected]");
 
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
    }
}


  默认的把这个对象输出为一般的XML:
<customer>
    <emailAddresses>[email protected]</emailAddresses>
    <emailAddresses>[email protected]</emailAddresses>
</customer>

下面逐一看每个注解的用法
1) @XmlElement
  
@XmlElement(name="email-address")
    private List<String> emailAddresses;
加上这个注解的话,则按自定义的xml标签名去输出某个属性,如下:
<customer>
    <email-address>[email protected]</email-address>
    <email-address>[email protected]</email-address>
</customer>

2) @XmlElementWrapper
  这个注解等于在最外面再包一层了,
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlElementWrapper(name="email-addresses")
    @XmlElement(name="email-address")
    private List<String> emailAddresses;

}
  输出:
<customer>
    <email-addresses>
        <email-address>[email protected]</email-address>
        <email-address>[email protected]</email-address>
    </email-addresses>
</customer>


3) @XmlList
  这个等于是在同一行中,把list中的输出,以空格形式分隔开来,
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    @XmlList
    private List<String> emailAddresses;
 
}


  输出:
  <customer>
    <emailAddresses>[email protected] [email protected]</emailAddresses>
</customer>

4)
@XmlList和 @XmlAttribute混合使用
      @XmlList
    @XmlAttribute
    private List<String> emailAddresses;

输出:
   <customer
    emailAddresses="[email protected] [email protected]"/>

看到没?就是同一行中逗号输出,并作为customer的一个属性


5)
  @XmlList 和 @XmlValue混用
   
    @XmlList
    @XmlValue
    private List<String> emailAddresses;
 

就是把emailAddress的list的值,作为<customer>的value  输出,结果如下:
<customer>[email protected] [email protected]</customer>
 

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