簡體   English   中英

java.lang.ClassCastException:錯誤

[英]java.lang.ClassCastException:Error

這是提供一些貨幣的XML文件片段。 它們都具有“貨幣名稱”,“購買外匯”,“出售外匯”等值。

<?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>

這是我的實際代碼:

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();
        }
    }

}

我想要做的就是從XML文件中獲取一些數據。 這是我對XML的第一篇著作。 我只希望它為每個元素打印“ kod”,“ Isim”和“ forex Selling”值。 但是,當我運行代碼時,出現此錯誤:

java.lang.ClassCastException:java.xml / com.sun.org.apache.xerces.internal.dom.DeferredElementImpl無法轉換為javaPaket.WONTWORK.main(WONTWORK的.java:36)

(第36行是“元素元素=(元素)節點;”第btw行。)

我該如何解決? 我從另一個站點復制了類似的代碼,只是更改了值。 但是我得到了這個錯誤.....

您會嘗試運行以下代碼嗎? 僅更改了for塊中的代碼。

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 doc = documentBuilder.parse(xmlFile);

        NodeList list = doc.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: " + element.getAttribute("Kod"));
                System.out.println("Para Birimi: " + element.getElementsByTagName("Isim").item(0).getTextContent());
                System.out.println("Forex Satis Ucreti: " + element.getElementsByTagName("ForexSelling").item(0).getTextContent()) ;

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

樣本輸出:

考德:AUD
Para Birimi:AVUSTRALYA DOLARI
外匯滿意指數:4.4521
柯德:DKK
Para Birimi:DANIMARKA KRONU
外匯滿意指數:0.93527

我認為您應該這樣做:

Element element = (org.w3c.dom.Element) node;

因為您也正在導入javax.lang.model.element.Element ,並且我懷疑強制轉換是使用該類型進行的(如stacktrace本身所暗示的)。

問題是您的進口貨不正確

import javax.lang.model.element.Element;

與...不同

import org.w3c.dom.Element;

這導致您的Java代碼中發生沖突。 嘗試使用此導入:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

舉一個簡單的例子,它正在工作。


嘗試清理並重新構建您的代碼。

最壞的情況下嘗試

  org.w3c.dom.Element element = (org.w3c.dom.Element) node;

好的,您的代碼存在一些涉及到人們已經提出的導入的問題,但是您還需要對代碼進行一些其他更改,以使其按您希望的方式工作。

首先,這里是我正在使用的XML,您沒有使代碼弄亂的root元素,但是您確實說這不是您正在使用的完整文件,因此我不確定是否需要查看它。

的test.xml:

<root>
    <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>
</root>

這是解析您的XML的Java:

    import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.HashMap;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Test{

    public static void main(String[] args) {

         /* 
        These are the values for the xml lines based on your file
        Unit            = 1
        Isim            = 2
        CurrencyName    = 3 
        ForexBuying     = 4
        ForexSelling    = 5
        BanknoteBuying  = 6
        BanknoteSelling = 7
        CrossRateUSD    = 8
         */

        //create a HashMap to map the loop count to the proper name
        //while printing, these are based on numbers commented above
        HashMap<Integer, String> mapOfItems = new HashMap<>();
        mapOfItems.put(1, "Unit");
        mapOfItems.put(2, "Isim");
        mapOfItems.put(3, "CurrencyName");
        mapOfItems.put(4, "ForexBuying");
        mapOfItems.put(5, "ForexSelling");
        mapOfItems.put(6, "BanknoteBuying");
        mapOfItems.put(7, "BanknoteSelling");
        mapOfItems.put(8, "CrossRateUSD");  

        try {
            File xmlFile = new File("test.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) {

                    //gather node with specific attribute, here item(2) == Kod 
                    String kodValue = node.getAttributes().item(2).getTextContent();

                    //create array based on text content, split be new line    
                    String[] values = node.getTextContent().split("\n");

                        System.out.println("\nKOD = "+ kodValue);
                        for (Integer e = 0; e < values.length; e++) {

                            //replaceAll() is for regex replacement of white space here
                            values[e] = values[e].replaceAll(
                                    "^\\s+|\\s+$|\\s*(\n)\\s*|(\\s)\\s*", "$1$2")
                                     .replace("\t"," ");

                            //just check to make sure null isn't being printed
                            if(mapOfItems.get(e)!= null)
                                System.out.println(mapOfItems.get(e)+" = "+values[e]);
                        }
                    }
                }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM