You could also do this using an XmlAdapter
Change your Bean class to look like this:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement
public class Bean {
@XmlElement(name = "ints")
@XmlJavaTypeAdapter(IndexAdapter.class)
int[] values;
}
The @XmlJavaTypeAdapter allows you to convert a property into another object that JAXB will marshal. This is similar to what was suggested above, without requiring your model to change. The adapter would look like:
import javax.xml.bind.annotation.adapters.XmlAdapter;
import forum.AdaptedArray.AdaptedArrayValue;
public class IndexAdapter extends XmlAdapter<AdaptedArray, int[]>{
@Override
public AdaptedArray marshal(int[] v) throws Exception {
AdaptedArray adaptedArray = new AdaptedArray();
for(int x=0; x<v.length; x++) {
adaptedArray.addValue(x, v[x]);
}
return adaptedArray;
}
@Override
public int[] unmarshal(AdaptedArray v) throws Exception {
int[] intArray = new int[v.ints.size()];
for(AdaptedArrayValue adaptedArrayValue : v.ints) {
intArray[adaptedArrayValue.index] = adaptedArrayValue.value;
}
return intArray;
}
}
The adapted value class would look like:
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlValue;
public class AdaptedArray {
@XmlElement(name="int")
List<AdaptedArrayValue> ints = new ArrayList<AdaptedArrayValue>();;
public void addValue(int index, int value) {
AdaptedArrayValue adaptedArrayValue = new AdaptedArrayValue();
adaptedArrayValue.index = index;
adaptedArrayValue.value = value;
ints.add(adaptedArrayValue);
}
public static class AdaptedArrayValue {
@XmlAttribute int index;
@XmlValue int value;
}
}