JAXB中各种常见注解小结

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

[code language=”java”]

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;
}

}

[/code]

这个是一个典型的POJO了,其中引用了对象emailAddress,是一个List,那么下面演示各类用法:
先看默认的调用代码如下:
[code language=”java”]
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("janed@example.com");
customer.getEmailAddresses().add("jdoe@example.org");

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
[/code]

默认的把这个对象输出为一般的XML:
<customer>
<emailAddresses>janed@example.com</emailAddresses>
<emailAddresses>jdoe@example.org</emailAddresses>
</customer>

下面逐一看每个注解的用法
1) @XmlElement

@XmlElement(name=”email-address”)
private List<String> emailAddresses;
加上这个注解的话,则按自定义的xml标签名去输出某个属性,如下:
<customer>
<email-address>janed@example.com</email-address>
<email-address>jdoe@example.org</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>janed@example.com</email-address>
<email-address>jdoe@example.org</email-address>
</email-addresses>
</customer>

3) @XmlList
这个等于是在同一行中,把list中的输出,以空格形式分隔开来,
[code language=”java”]
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

@XmlList
private List&lt;String&gt; emailAddresses;

}
[/code]

输出:
<customer>
<emailAddresses>janed@example.com jdoe@example.org</emailAddresses>
</customer>

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

输出:
<customer
emailAddresses=”janed@example.com jdoe@example.org”/>

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

5)
@XmlList 和 @XmlValue混用

@XmlList
@XmlValue
private List<String> emailAddresses;

就是把emailAddress的list的值,作为<customer>的value  输出,结果如下:
<customer>janed@example.com jdoe@example.org</customer>

标签