给出以下xml代码:
<root>
<vector>{1, 2, 3, 4, 5}</vector>
</root>
是否可以将元素<vector>
解组为5元素数组,以便:
array = {1, 2, 3, 4, 5}
在我尝试这样做时,我编写了一些代码,但它无法正确地将<vector>
拆分为一个数组,其中每个数字都是一个单独的元素:
@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;
}
}
答案 0 :(得分:2)
你需要一个XmlAdapter,如下所示:
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;
}
}
然后使用@XmlJavaTypeAdapter:
注释您的元素@XmlJavaTypeAdapter(VectorAdapter.class)
@XmlElement(name = "vector")
public void setVector(final int[] vector) {
this.vector = vector;
}