Seeta Somagani
Seeta Somagani

Reputation: 787

How to create element and set custom attribute to map a simple type class property

@XmlRootElement(name="flowPane")
public class Image implements Serializable {
    public  String name;
    public  String description;
}

Bound to

<flowPane>
    <label text="name"/>
    <label text="description"/>
</flowPane>

Tried simply placing @XmlAttribute and @XmlElement annotations on the name and description properties but neither is the solution that I'm looking for.

Upvotes: 1

Views: 291

Answers (2)

bdoughan
bdoughan

Reputation: 149047

Using Standard JAXB APIs

In order to get the same element to appear multiple times in an XML document you are going to need a List property. Note in the example below label will have a property mapped to the text attribute.

@XmlRootElement(name="flowPanel")
@XmlAccessorType(XmlAccessType.FIELD)
public class Image implements Serializable {

   @XmlElement(name="label").
   private List<Label> labels;

}

@XmlPath extension in EclipseLink JAXB (MOXy)

If you are using EclipseLink MOXy as your JAXB (JSR-222) provider then you could leverage the @XmlPath extension we added for this use case.

@XmlRootElement(name="flowPane")
public class Image implements Serializable {
    @XmlPath("label[1]/@text")
    public  String name;

    @XmlPath("label[1]/@text")
    public  String description;
}

For More Information

I have written more about this on my blog:

Upvotes: 1

Filip Nguyen
Filip Nguyen

Reputation: 1039

You must wrap the fields with a new class

@XmlRootElement(name="flowPanel")
public class Image implements Serializable {

    public static class Label {
        @XmlAttribute()
        public String text;

        public Label(){}

        public Label(String text) {
            this.text = text;
        }   
    }

    @XmlElement(name="label")
    public Label name;
    @XmlElement(name="label")
    public Label description;    
}

Upvotes: 1

Related Questions