Commit ba693fc6 by Patryk Czarnik

Analiaza Walut DOM - wersja 1 (getElementsByTagName)

parent e6d01bd5
package przyklady_dom;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
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 java.io.IOException;
public class AnalizaWalut1 {
public static void main(String[] args) {
String szukanyKod = "USD";
// chcemy obliczyć średni kurs podanej waluty z całego pliku
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
System.out.println("Mam DocumentBuilder: " + builder);
Document doc = builder.parse("waluty_2022.xml");
System.out.println("Dokument wczytany: " + doc);
Element root = doc.getDocumentElement();
System.out.println("Nazwa elememtu głównego: " + root.getTagName());
double suma = 0;
int ilosc = 0;
NodeList rates = root.getElementsByTagName("Rate");
final int nRates = rates.getLength();
for (int i = 0; i < nRates; i++) {
Element rate = (Element) rates.item(i);
// zakładamy, że każdy Rate na pewno posiada podelement Code; gdyby nie miał, to będzie wyjątek
Element elementCode = (Element) rate.getElementsByTagName("Code").item(0);
String code = elementCode.getTextContent();
if(code.equalsIgnoreCase(szukanyKod)) {
Element elementMid = (Element) rate.getElementsByTagName("Mid").item(0);
double mid = Double.parseDouble(elementMid.getTextContent());
suma += mid;
ilosc++;
}
}
double srednia = suma / ilosc;
System.out.println("Średni kurs waluty " + szukanyKod + " = " + srednia);
} catch (ParserConfigurationException | SAXException | IOException 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