下面就来以一个例子小结下,加深学习:
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("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); } }
默认的把这个对象输出为一般的XML:
<customer>
<emailAddresses>janed@example.com</emailAddresses>
<emailAddresses>jdoe@example.org</emailAddresses>
</customer>
下面逐一看每个注解的用法
1) @XmlElement
@XmlElement(name="email-address")
private List<String> emailAddresses;
加上这个注解的话,则按自定义的xml标签名去输出某个属性,如下:
<email-address>janed@example.com</email-address>
<email-address>jdoe@example.org</email-address>
2) @XmlElementWrapper
这个注解等于在最外面再包一层了,sans-serif; font-size:14px; line-height:25.2000007629395px">@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlElementWrapper(name="email-addresses")
@XmlElement(name="email-address")
}
输出:
<email-addresses>
</email-addresses>
3) @XmlList
这个等于是在同一行中,把list中的输出,以空格形式分隔开来,
@XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Customer { @XmlList private List<String> emailAddresses; }
输出:
<customer>
<emailAddresses>janed@example.com jdoe@example.org</emailAddresses>
4)
@XmlList和 @XmlAttribute混合使用
@XmlList
@XmlAttribute
<customer
emailAddresses="janed@example.com jdoe@example.org"/>
看到没?就是同一行中逗号输出,并作为customer的一个属性
5)
@XmlList 和 @XmlValue混用
@XmlValue
就是把emailAddress的list的值,作为<customer>的value 输出,结果如下:
<customer>janed@example.com jdoe@example.org</customer>
本文来至:http://jackyrong.iteye.com/blog/1890669
原文链接:https://www.f2er.com/xml/297340.html