2015-06-10 110 views
1

鑑於以下XML代碼:我可以將單個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; 
    } 
} 

回答

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; 
} 
+0

謝謝你,那也正是我想要:) – 5had3sofQu4rtz

相關問題