Here is the XML file snippet that gives some currencies. All of them has values like "currency name", "forex buying", "forex selling" etc...
<?xml version="1.0" encoding="UTF-8"?>
<Currency CrossOrder="1" Kod="AUD" CurrencyCode="AUD">
<Unit>1</Unit>
<Isim>AVUSTRALYA DOLARI</Isim>
<CurrencyName>AUSTRALIAN DOLLAR</CurrencyName>
<ForexBuying>4.4233</ForexBuying>
<ForexSelling>4.4521</ForexSelling>
<BanknoteBuying>4.4030</BanknoteBuying>
<BanknoteSelling>4.4789</BanknoteSelling>
<CrossRateUSD>1.3839</CrossRateUSD>
<CrossRateOther/>
</Currency>
<Currency CrossOrder="2" Kod="DKK" CurrencyCode="DKK">
<Unit>1</Unit>
<Isim>DANIMARKA KRONU</Isim>
<CurrencyName>DANISH KRONE</CurrencyName>
<ForexBuying>0.93070</ForexBuying>
<ForexSelling>0.93527</ForexSelling>
<BanknoteBuying>0.93004</BanknoteBuying>
<BanknoteSelling>0.93742</BanknoteSelling>
<CrossRateUSD>6.5827</CrossRateUSD>
<CrossRateOther/>
</Currency>
And here is my actual code:
import javax.lang.model.element.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class PasteClass {
public static void main(String[] args) {
try {
File xmlFile = new File("TCMB2.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.parse(xmlFile);
NodeList list = document.getElementsByTagName("Currency");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Kod: "
+ ((org.w3c.dom.Document) element)
.getElementsByTagName("Kod").item(0).getTextContent());
System.out.println("Para Birimi: "
+ ((org.w3c.dom.Document) element)
.getElementsByTagName("Isim").item(0).getTextContent());
System.out.println("Forex Satis Ucreti: "
+ ((org.w3c.dom.Document) element)
.getElementsByTagName("ForexSelling").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
What I want to do is, simply grabbing some data from an XML file. This is my first work with XML. I just want it to print "kod", "Isim" and "forex Selling" values for each element. But when I run the code, I get this error:
java.lang.ClassCastException: java.xml/com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to java.compiler/javax.lang.model.element.Element at javaPaket.WONTWORK.main(WONTWORK.java:36)
(36th line is the "Element element = (Element) node;" line btw. )
How can I fix that? I copied the similar code from the other site and just changed the values. Yet I got this error.....