I would like to marshall a Collection as nested attributes.
Right now I have:
@Xm开发者_开发百科lElement(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
:
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.
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.
To marshal the collection values as attributes, you use it like this:
@XmlPath("entry/@id")
public Collection<Integer> getSizes(){ ... }
精彩评论