Hi all I have an XML file in java which holds a 2d array of numbers it looks something like
<tableNumbers>
<row id="0">
<column id="0"> 4 </column>
<column id="1"> 2 </column>
<column id="2"> 5 </column>
<column id="3"> 6 </column>
</row>
<row id="1">
<column id="0"> 5 </column>
<column id="1"> 10 </column>
<column id="2"> 7 </column>
<column id="3"> 9 </column>
</row>
</tableNumbers>
Now every row in the table has the same number of colums and what I am trying to do is cycle through the xml and store the number from the XML file into an Integer array. (e.g. row 0 column 0 would be stored in numbers[0][0].
The code I currently have is:
public static Integer[][] getNumbers(File file, int noRows, int noColums){
Integer[][] numbersArray = new Integer[noRows][noColumns];
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
try {
Document document = docBuilderFactory.newDocumentBuilder().parse(file);
Element rootElement = document.getDocumentElement();
NodeList rowList = rootElement.getElementsByTagName("row");
if ((rowList != null))
for (int i = 0; i < rowList.getLength(); i++) {
NodeList columnsList = rowList.item(i).getChildNodes();
if ((columnsList != null))
for (int j = 0; j < columnsList.getLength(); j++) {
Element number = (Element) columnsList.item(j);
System.out.println("(" +i + "," + j + ") " + number.getNodeValue());
numbersArray[i][j] = number.getNodeValue();
}
}
return numbersArray;
}
catch (Exception c){}
return null;
}
A few lines from the standard the output are:
(0,0) null
(0,1) null
(0,2) null
(0,3) null
(1,0) null
(1,1) null
(1,2) null
(1,3) null
The value which is returned from all the cells is null. I know the error is reading from the xml file. If anyone could show me where I am going wrong I would be most grateful
I would add the following:
Since you may have an empty element. Also, I’m using
getTextContent()method fromNodedeclaration.