I'm trying to convert the XML below into a JAXB annotated class but I'm having trouble thinking of a solution where an element repeats within an XML root.
<addresses xmlns='http://jabber.org/protocol/address'>
<address type='to' jid='hildjj@jabber.org/Work' />
<address type='cc' jid='jer@jabber.org/Home' />
</addresses>
I have this class that maps to the XML, I want an element 'address' with attributes 'type' and 'jid' to form within the XML Root Element 'addresses' for each item in the list that I pass in the constructor.
@XmlRootElement(name = "addresses", namespace = "http://jabber.org/protocol/address")
@XmlAccessorType(XmlAccessType.FIELD)
public class Addresses {
@XmlElement
private List<String> address;
private Addresses() {
// Private no-args default constructor for JAXB.
}
public Addresses(List<String> address) {
this.address = address;
}
}
For example, if I pass a list ("User1", "User2", "User3") when instantiating the object, the resulting XML will look like:
<addresses xmlns='http://jabber.org/protocol/address'>
<address type='to' jid='User1' />
<address type='to' jid='User2' />
<address type='to' jid='User3' />
</addresses>
I managed to achieve this by creating two classes Address and Addresses. The Addresses root element will take a list of class 'Address' as the element input.
@XmlRootElement(name = "addresses", namespace = "http://jabber.org/protocol/address")
@XmlAccessorType(XmlAccessType.FIELD)
public class Addresses {
@XmlElement
private List<Address> address; //List of type address
private Addresses() {
// Private no-args default constructor for JAXB.
}
public Addresses(List<String> address) {
this.address = address;
}
}
This is the address class with the attributes 'to' and 'jid'. It takes an input jid of type String in the constructor.
@XmlRootElement(name = "address")
@XmlAccessorType(XmlAccessType.FIELD)
public class Address {
@XmlAttribute
private String to = 'to';
@XmlAttribute
private String jid;
private Address() {
// Private no-args default constructor for JAXB.
}
public Address(String jid) {
this.jid = jid;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.