Can I unmarshal a single xml property to a multi element array?

35 views Asked by At

Given the following xml code:

<root>
  <vector>{1, 2, 3, 4, 5}</vector>
</root>

Is it possible to unmarshal the element <vector> into a 5 element array, such that:

array = {1, 2, 3, 4, 5}

In my attempt to do this I have written some code, but it fails to correctly split the <vector> into an array where each number is a separate element:

@XmlType(propOrder = {"vector"})
@XmlRootElement(name = "root")
public class Data
{
  // class data
  private int[] vector;

  @XmlElement(name = "vector")
  public void setVector(int[] vector)
  {
    this.vector = vector;
  }

  public int[] getVector()
  {
    return vector;
  }
}
1

There are 1 answers

1
fgwe84 On BEST ANSWER

You need a XmlAdapter, something like this:

public class VectorAdapter extends XmlAdapter<String, int[]> {

    @Override
    public int[] unmarshal(final String v) throws Exception {
        final String[] strs = v.substring(1, v.length() - 1).split(",");
        final int[] vector = new int[strs.length];
        for (int i = 0; i < strs.length; i++) {
            vector[i] = Integer.parseInt(strs[i].trim());
        }
        return vector;
    }

    @Override
    public String marshal(final int[] v) throws Exception {
        return null;
    }
}

Then annotate your element with @XmlJavaTypeAdapter:

@XmlJavaTypeAdapter(VectorAdapter.class)
@XmlElement(name = "vector")
public void setVector(final int[] vector) {
    this.vector = vector;
}