XML File
Create new package named data. In this package, create new xml file named products.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product>
<id>p01</id>
<name>name 1</name>
<price currency="usd">20</price>
<quantity>5</quantity>
<weight unit="kg">2.1</weight>
<date format="dd/MM/yyyy">02/03/2017</date>
<status>true</status>
</product>
<product>
<id>p02</id>
<name>name 2</name>
<price currency="eur">12</price>
<quantity>3</quantity>
<weight unit="kg">6.5</weight>
<date format="dd/MM/yyyy">24/11/2018</date>
<status>true</status>
</product>
<product>
<id>p03</id>
<name>name 3</name>
<price currency="aud">13</price>
<quantity>1</quantity>
<weight unit="kg">7.8</weight>
<date format="dd/MM/yyyy">14/10/2018</date>
<status>false</status>
</product>
</products>
Run Application
Create new package, named demo. In this package, create new java class, named Main as below
package demo;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
public class Main {
private static void sum() {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse("src\\data\\products.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
int result = Integer.parseInt(xpath.compile("sum(//quantity)").evaluate(document));
System.out.println("Quantities: " + result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public static void main(String[] args) {
sum();
}
}
Output
Quantities: 9