I’m having some problems reading data from XML and load it into an array. This is the code I have:
private void LoadMap(String path) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( );
Document document = null;
try {
DocumentBuilderFactory builder = DocumentBuilderFactory.newInstance();
builder.setIgnoringElementContentWhitespace(true);
document = builder.newDocumentBuilder().parse(path);
Element Map = document.getDocumentElement();
Node nodeTileset = Map.getElementsByTagName("tileset").item(0);
Node nodeData = Map.getElementsByTagName("data").item(0);
NamedNodeMap attribTileset = nodeTileset.getAttributes();
layers = Integer.parseInt(attribTileset.getNamedItem("layers").getNodeValue());
width = 50;
height = 50;
name = Map.getAttribute("name");
// Creamos el array y lo rellenamos con los valores
array = new int[layers][height][width];
Node layer, row, column;
for(int i = 0; i < layers; i++) {
layer = nodeData.getChildNodes().item(i);
for(int j = 0; j < height; j++) {
if(layer.getNodeType() != Node.TEXT_NODE) {
row = layer.getChildNodes().item(j);
for(int k = 0; k < width; k++) {
if(row.getNodeType() != Node.TEXT_NODE) {
column = row.getChildNodes().item(k);
if(column.getNodeType() != Node.TEXT_NODE) {
array[i][j][k] = Integer.parseInt(column.getTextContent());
}
}
}
}
}
}
}
catch(ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
The problem is that you have ignored the fact that there are whitespace-only text nodes in your input XML, which take up index positions when using
getChildNodes().item(i). You must check each node type and ignore non-element nodes so that you process only the ones you want.From your input, I can tell that there is a whitespace node between row each row tag, so
where i == 1, returns a text node. Since the text node has no child nodes,
columnis null at this point, resulting in the NPE.This also means you can’t blindly use the counts from the
<tileset>tag as loop boundaries. You must test each node type before you process it and count actually processed nodes until you reach the expected totals (which are wrong, by the way; there are 50 rows and 50 columns).