简体   繁体   English

JAXB在一个步骤中将XmlElement和XmlAttribute的集合封送处理

[英]JAXB marshall a Collection to a XmlElement and a XmlAttribute in one step

I would like to marshall a Collection as nested attributes. 我想将Collection编组为嵌套属性。

Right now I have: 现在我有:

@XmlElement(name="entry")
public Collection<Integer> getSizes(){ ... }

which returns: 返回:

<entry>1</entry>
<entry>2</entry>

But I would like to get: 但我想得到:

<entry id="1"/>
<entry id="2"/>

Is this possible without new classes? 没有新课程,这可能吗?

Seems to be impossible without new classes at all. 如果没有新课程,似乎是不可能的。 Use XmlAdapter : 使用XmlAdapter

class EntryAdapter extends XmlAdapter<EntryAdapter.Entry, Integer>
{
    public EntryAdapter.Entry marshal(Integer id) {
        return new Entry(id);
    }

    public Integer unmarshal(Entry e) {
        return e.getId();
    }

    static class Entry 
    {
        private Integer id;

        public Entry() {}
        public Entry(Integer id) { this.id = id; }

        @XmlAttribute
        public Integer getId() { return id; }
        public void setId(Integer id) { this.id = id; }
    }
}

- -

@XmlElement(name="entry")  
@XmlJavaTypeAdapter(EntryAdapter.class)
public Collection<Integer> getSizes(){ ... }

As the accepted answer says, XmlAdapter is the standard JAXB solution. 正如公认的答案所说, XmlAdapter是标准的JAXB解决方案。

But if you are using EclipseLink MOXy as your JAXB provider and can use one of its extensions, namely @XmlPath , it can be used to achieve the same result. 但是,如果您将EclipseLink MOXy用作JAXB提供程序,并且可以使用其扩展名之一,即@XmlPath ,则可以使用它来实现相同的结果。

To marshal the collection values as attributes, you use it like this: 要将集合值封送为属性,可以像这样使用它:

@XmlPath("entry/@id")
public Collection<Integer> getSizes(){ ... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM