将XML转换为JAXB带注释的类

时间:2016-08-23 05:49:17

标签: java xml jaxb

我正在尝试将下面的XML转换为JAXB注释类,但是我在思考一个元素在XML根目录中重复的解决方案时遇到了麻烦。

   <addresses xmlns='http://jabber.org/protocol/address'>
       <address type='to' jid='hildjj@jabber.org/Work' />
       <address type='cc' jid='jer@jabber.org/Home' />
   </addresses>

我有这个映射到XML的类,我想要一个带有属性'type'和'jid'的元素'address',以便在我传递的列表中的每个项目的XML根元素'地址'中形成构造

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

例如,如果在实例化对象时传递一个列表(“User1”,“User2”,“User3”),则生成的XML将如下所示:

   <addresses xmlns='http://jabber.org/protocol/address'>
       <address type='to' jid='User1' />
       <address type='to' jid='User2' />
       <address type='to' jid='User3' />
   </addresses>

1 个答案:

答案 0 :(得分:0)

我设法通过创建两个类Address和Addresses来实现这一目标。 Addresses根元素将使用“Address”类列表作为元素输入。

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

这是具有'to'和'jid'属性的地址类。它在构造函数中使用String类型的输入jid。

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