Commit 2ea469a8 by Patryk Czarnik

XPath waluty v3 sum / count

parent a3504f9d
package przyklady_xpath;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
public class WalutyXPath3 {
public static void main(String[] args) {
String szukanyKod = "USD";
// chcemy obliczyć średni kurs podanej waluty z całego pliku
System.out.println("Konfiguracja");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
XPathFactory xpf = XPathFactory.newInstance();
try {
XPath xpath = xpf.newXPath();
DocumentBuilder builder = factory.newDocumentBuilder();
System.out.println("Czytanie pliku");
Document doc = builder.parse("waluty_2022.xml");
String ratesPath = "//Rate[Code = '" + szukanyKod + "']";
String path = "sum(" + ratesPath + "/Mid) div count(" + ratesPath + ")";
System.out.println("Ewaluacja wyrażenia " + path);
double srednia = (double)xpath.evaluate(path, doc, XPathConstants.NUMBER);
System.out.println("Średni kurs waluty " + szukanyKod + " = " + srednia);
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
throw new RuntimeException(e);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment