【问题标题】:java.lang.ClassCastException:Errorjava.lang.ClassCastException:错误
【发布时间】:2019-01-23 10:45:06
【问题描述】:

这是给出一些货币的 XML 文件 sn-p。它们都具有“货币名称”、“外汇购买”、“外汇销售”等值......

<?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 无法转换为 java.compiler/javax.lang.model.element.Element 在 javaPaket.WONTWORK.main(WONTWORK.java:36)

(第36行是“元素元素=(元素)节点;”顺便说一句。)

我该如何解决这个问题?我从另一个站点复制了类似的代码,只是更改了值。然而我得到了这个错误.....

【问题讨论】:

  • 可能会用到应该看看这个stackoverflow.com/questions/13296583/…
  • 已经看过但无法正确理解解决方案...因为我的代码与他的不同:/
  • 检查我的代码,它与您的示例不同,使您能够正确解析文档。您要打印的值看起来很奇怪,因为它们位于 XML 元素中的不同位置(即“kod”、“Isim”和“forex Selling”),但我的示例确实为您提供了每个值您正在寻找。
  • Kod="AUD" 是货币标签的一种属性。所以你必须使用'getAttribute'代替'getTag'。

标签: java xml


【解决方案1】:

你会尝试运行下面的代码吗?仅更改了 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();
    }
}

样本输出:

Kod:澳元
Para Birimi: AVUSTRALYA DOLARI
外汇 Satis Ucreti:4.4521
科德:丹麦克朗
帕拉比里米:DANIMARKA KRONU
外汇 Satis Ucreti:0.93527

【讨论】:

  • 感谢它的工作。所以看起来问题是将“((org.w3c.dom.Document)”插入“元素”。它由eclipse IDE本身提出,但它完全没有必要大声笑
【解决方案2】:

问题是您的导入不正确

import javax.lang.model.element.Element;

不一样
import org.w3c.dom.Element;

这会导致您的 java 代码发生冲突。 试试这个 Imports:

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;

【讨论】:

  • 我删除了所有的导入,然后把你的放在那里。还是行不通。当我运行代码时,它说:“java.lang.ClassCastException:java.xml/com.sun.org.apache.xerces.internal.dom.DeferredElementImpl 不能转换为 java.xml/org.w3c.dom.Document at javaPaket.WONTWORK.main(WONTWORK.java:36)"
【解决方案3】:

我认为你应该这样做:

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

因为您还导入了 javax.lang.model.element.Element,并且我怀疑该类型正在发生转换(正如堆栈跟踪本身所暗示的那样)。

【讨论】:

  • 没用。当我像你提到的那样编辑我的代码时,它说我要像我在我的线程中发布的那样投射它。当我这样做时,我遇到了运行时错误,哈哈。
【解决方案4】:

好的,您的代码存在一些问题,涉及人们已经提出的导入,但您还需要对代码进行一些其他更改,以使其按照您想要的方式工作。

首先这里是我正在使用的 XML,您没有弄乱代码的根元素,但您确实说这不是您使用的完整文件,所以我不确定您是否需要查看它.

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

【讨论】:

  • 我还没有尝试过这段代码,但即使它可以工作,这段代码也有一些我不知道的关于 Java 的主题。我在 google & youtube 中找到的示例没有使用任何地图或 X.value 方法。他们的代码就像我在这里的帖子一样。不能更简单吗?
  • 嘿,我刚刚意识到我在线程中使用了错误的值。我的结果中不需要“Kod”值。由于它是“属性”,因此我不在乎。但我需要访问代码中的一些/或所有元素。 (即 ForexBuying、CurrencyName、Isim、Unit....) 那么,现在有没有更简单的代码版本?提前致谢。
  • @blackwater7,我的代码中已经提供了您所要求的内容,我会给您一个更简洁的示例,但是您确实已经接受了答案,并且我的版本已经根据您的问题起作用,所以除非您仍然需要帮助,否则我没有看到更改任何内容的好处。我使用 HashMap 是因为它是一种近乎完美的 Java 数据类型,用于将循环计数映射到“元素”名称。
猜你喜欢
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多