I am very new to java and xml. I am trying to find a way to make the summation of the amount but I am not sure how to do this. I tried a couple of things already but it didn't work. Thanks a lot for your help.
for (int i = 0; i < clients.getLength(); i++) {
Element client = (Element) clients.item(i);
String name = client.getAttribute("name");
NodeList transactions = client.getElementsByTagName("transaction");
for(int j=0; j<transactions.getLength(); j++) {
Element transaction = (Element) transactions.item(j);
int amount = Integer.parseInt(transaction.getAttribute("amount"));
}
System.out.println("Client name : " +name);
System.out.println("Sum : " );
}
try this
for (int i = 0; i < clients.getLength(); i++) {
Element client = (Element) clients.item(i);
String name = client.getAttribute("name");
NodeList transactions = client.getElementsByTagName("transaction");
int sum =0;
for(int j=0; j<transactions.getLength(); j++) {
Element transaction = (Element) transactions.item(j);
sum = sum + Integer.parseInt(transaction.getAttribute("amount"));
}
System.out.println("Client name : " +name);
System.out.println("Sum : " + sum );
}
This kind of thing is much easier with XPath (even if you have to use Java and DOM, which you probably don't).
XPath xpath = XPathFactory.newInstance().newXPath();
for (int i = 0; i < clients.getLength(); i++) {
Element client = (Element) clients.item(i);
int sum = (int)xpath.evaluate("sum(transaction/@amount)",
client, XPathConstants.NUMBER);
System.out.println("Client name : " + client.getAttribute("name"));
System.out.println("Sum : " + sum );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.