2014-10-01 30 views
0

我目前正在從一個XML文件中獲取一組數據的項目中工作。 XML文件具有多個存儲不同數據類型(字符串,整數和布爾值)的節點。 Java以字符串形式返回每個字符串,因爲您可以將它們轉換爲程序中正確的數據類型。當節點返回時,我想將它們放入適當類型的數組中,並將這些數組中的每個數組存儲在主數組中,以供將來在我的程序中使用。在我的XML文件中,我希望有一個節點,其中可以有多個具有相同標記的子節點,這就是爲什麼我使用多維數組的原因。是否可以在一個數組數組中存儲多種類型的數組?

我試圖使用Object[][]Variable[][]沒有成功,除非我缺少一些簡單的東西(可能是這種情況)。

XML例如:

<parent> 
    <child1>string</child1> 
    <child2>int</child2> 
    <child2>int</child2> 
    <child3>boolean</child3> 
</parent> 

Java示例:

NodeList nList = doc.getElementsByTagName("parent"); 
NodeList nlAttributes = nList.item(cardId).getChildNodes(); 
List<String> lElements = new ArrayList<String>(); 
List<String> lRepeateElement = new ArrayList<String>(); 
for(int i = 0; i <nlAttributes.getLength(); i++){ 
    if(nlAttributes.item(i).getNodeType()!=3&&nlAttributes.item(i).getNodeType()!=8){ 
     if(nlAttributes.item(i).getNodeName().equals("effect")){ 
      lRepeateElement.add(nlAttributes.item(i).getTextContent()); 
     }else{ 
      lElements.add(nlAttributes.item(i).getTextContent()); 
     } 
    } 
} 
aRepeatElements = new String[lRepeateElement.size()]; 
for(int i = 0; i<lRepeateElement.size(); i++){ 
    aRepeatElements[i]=lRepeateElement.get(i); 
} 
sElements = new String[lElements.size()]; 
oElements = new Variable[lElements.size()+1][]; //oElements = new Object[lElements.size()+1][]; 
for(int i = 0; i<lElements.size(); i++){ 
    if(i==4){ 
     oElements[i]=aRepeatElements;//incompatible types: String[] cannot be converted to Variable/Object[] -> this still exists after attempting to casts 
    }else{ 
     sElements[i]=lElements.get(0); 
     String[] temp = new String[1]; 
     temp[0]=sElements[i];//incompatible types: String[] cannot be converted to Variable/Object[] -> this still exists after attempting to casts 
     oElements[i]=temp; 
     lElements.remove(0); 
    } 
} 
+0

對象[] []應該在將'int'轉換爲'Integer'後工作(對於其他原語也是如此)。 – 2014-10-01 23:07:32

+0

是的工作......就像我上面說過的,簡單的說我錯過了。非常感謝! – TehNoiseBomb 2014-10-01 23:12:36

+0

相關知識:-) ...將我的評論轉換爲答案。 – 2014-10-01 23:25:10

回答

0

Object[][]將解決這個問題,因爲一切都在Java是一種Object。除了基元以外的所有東西,就是!

爲了克服這個問題,所有你需要做的是包裹原語:

  • int - >Integer
  • boolean - >Boolean
  • ...
相關問題