繁体   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