Commit d9e3c2d9 by Patryk Czarnik

waluty - wersja DOM

parent 34cdfc92
package p20_xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class Waluty1_Dom {
public static void main(String[] args) {
File plik = new File("pliki/waluty2023.xml");
String waluta = "EUR";
System.out.println("Startujemy");
long t1 = System.nanoTime();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(plik);
long t2 = System.nanoTime();
double min = Double.MAX_VALUE, max = 0, sum = 0;
int count = 0;
NodeList tables = doc.getElementsByTagName("ExchangeRatesTable");
final int n = tables.getLength();
for(int i = 0; i < n; i++) {
Element table = (Element) tables.item(i);
// ryzyko NPE, gdyby plik był niepoprawny:
String effectiveDate = table.getElementsByTagName("EffectiveDate").item(0).getTextContent();
// System.out.println(effectiveDate);
NodeList rates = table.getElementsByTagName("Rate");
final int m = rates.getLength();
for(int j = 0; j < m; j++) {
Element rate = (Element) rates.item(j);
String code = rate.getElementsByTagName("Code").item(0).getTextContent();
if(code.equals(waluta)) {
double mid = Double.parseDouble(rate.getElementsByTagName("Mid").item(0).getTextContent());
count++;
sum += mid;
if(mid < min) min = mid;
if(mid > max) max = mid;
}
}
}
long t3 = System.nanoTime();
Runtime runtime = Runtime.getRuntime();
long pamiec = runtime.totalMemory() - runtime.freeMemory();
System.out.printf("Czas czytania pliku: %.6f s%n", (t2-t1) * 1e-9);
System.out.printf("Czas liczenia : %.6f s%n", (t3-t2) * 1e-9);
System.out.printf("Czas łączny : %.6f s%n", (t3-t1) * 1e-9);
System.out.printf("Zajęta pamięć : %,d B%n", pamiec);
System.out.println("Count: " + count);
if(count > 0) {
System.out.println("Avg: " + (sum / count));
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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