大家好,我在Java中有一个XML文件,其中包含一个二维数组,看起来像
4
2
5
6
5
10
7
9
现在,表中的每一行都有相同数量的列,而我想做的是遍历xml并将该XML文件中的数字存储到Integer数组中. (例如,第0行第0列将存储在数字[0] [0]中.
我目前拥有的代码是:
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;
}
标准输出的几行是:
(0,0) null
(0,1) null
(0,2) null
(0,3) null
(1,0) null
(1,1) null
(1,2) null
(1,3) null
从所有单元格返回的值为空.我知道错误是从xml文件读取的.如果有人可以告诉我我要去哪里错了,我将不胜感激
解决方法:
我将添加以下内容:
Element number = (Element) columnsList.item(j);
if ("column".equals(number.getTagName())) }
System.out.println("(" +i + "," + j + ") " + number.getTextContent());
}
由于您可能有一个空元素.另外,我正在使用Node声明中的getTextContent()方法.
标签:xml,java
来源: https://codeday.me/bug/20191201/2080604.html