Buhake Sindi
Buhake Sindi

Reputation: 89189

JAXB: Mapping XML attribute value to custom data type

Suppose you have an XML containing an element as follows:

<card expirydate="012017"> <!-- various attributes exists but it's unnecessary for this case.

As you can see the first 2 characters dictates the month and the last 4 digits represents the year.

I will like to model it to a Month object like so:

/**
 * @author Buhake Sindi
 * @since 19 January 2015
 *
 */
public class Month implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -3746059271757081350L;

    private int month;
    private int year;

    /**
     * 
     */
    public Month() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @param month
     * @param year
     */
    public Month(int month, int year) {
        super();
        PreConditions.checkArgument(month >= 1 && month <= 12, "Invalid month specified.");
        this.month = month;
        this.year = year;
    }

    /**
     * @return the month
     */
    public int getMonth() {
        return month;
    }

    /**
     * @param month the month to set
     */
    public void setMonth(int month) {
        this.month = month;
    }

    /**
     * @return the year
     */
    public int getYear() {
        return year;
    }

    /**
     * @param year the year to set
     */
    public void setYear(int year) {
        this.year = year;
    }
}

What type of Converter/Adapter do I use that maps an attribute to an Object and vice versa in JAXB?

Upvotes: 1

Views: 668

Answers (1)

bdoughan
bdoughan

Reputation: 149047

You would create an XmlAdapter for this use case that converts a Month to/from a String.

public class MonthAdapter extends XmlAdapter<String, Month>

Then in the marshal/unmarshal methods you put your own custom logic for converting between Month and String.

Upvotes: 1

Related Questions