I have a XML file that I am trying to read and transform into objects. I want to transform and put all the locations in a array filled with Location objects wich are defined by a film id, a date and a amount.
Here is my XML file :
Here is my code to scan the location XML section :
public void findLocations() throws ParseException {
NodeList nList = document.getElementsByTagName("location");
Location[] locations = new Location[nList.getLength()];
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
locations[temp] = new Location(getTagValue("filmid", eElement), dateChanger(getTagValue("date", eElement)), getTagValue("amount", eElement));
System.out.println(locations[temp].getAmount()); //Outputs the good values.
}
}
System.out.println(locations[0].getAmount()); //Output : 5$
System.out.println(locations[1].getAmount()); //Output : 5$
System.out.println(locations[2].getAmount()); //Output : 5$
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
The problem seems that my array is getting filled 3 times with the same location and ends up filled 3 time with the last location. The objects otherwise are well formed, so I imagine I got that part right.
You could use XPath instead…
Which outputs…
Updated After Feed-back
The
Locationclass is maintaining astaticreference to it’s class fields, this means that changing the value for the field will change it for all instances of that class.Remove the
staticreferences and it should solve the problem.