这里是ClassCastException错误

时间:2016-06-05 13:05:36

标签: java xml database tags classcastexception

当我尝试读取/打印出xml数据库时,我收到了错误代码 -

这里是文件的代码 -

 package xml;

import java.io.IOException;
import java.io.FileInputStream;

import javax.lang.model.element.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.FileNotFoundException;

public class MyDomParser {

    public static void main(String[] args){
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse("C://users/user/desktop/xml/xml/src/xml/people.xml");
        NodeList personList = doc.getElementsByTagName("person");
        for (int i=0; i<personList.getLength(); i++){
            Node p = personList.item(i);
            if(p.getNodeType()==Node.ELEMENT_NODE){
                Element person = (Element) p;
                String id = (String) ((DocumentBuilderFactory)person).getAttribute("id");
                NodeList nameList = ((Node)person).getChildNodes();
                for(int j=0; j< ((NodeList)nameList).getLength(); j++){
                    Node n = nameList.item(j);
                    if(n.getNodeType()==Node.ELEMENT_NODE){
                        Element name = (Element) n;
                        System.out.println("Person " + id + ":" + name.getSimpleName() + "=" + ((Node)name).getTextContent());

                    }

                }
            //  ((Document) r).getAttributes().getNamedItem("author").getNodeValue()
            }
        }
    } catch (ParserConfigurationException e) {

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

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

    e.printStackTrace();

    }
}
}

这是我执行并尝试运行上述代码时收到的错误消息:

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to javax.lang.model.element.Element
at xml.MyDomParser.main(MyDomParser.java:27)

我的代码有什么问题?我正在使用Eclipse IDE来输入和编辑我的代码。我应该使用另一个IDE吗?

&#34; people.xml&#34;文件也可以在下面看到:

<?xml version ="1.0"?>

<people>

<person id ="1">
    <lastname>Doe</lastname>
    <firstname>John</firstname>
    </person>
    <person id="2">
    <lastname>Smith</lastname>

    <firstname>Jim</firstname>
    </person>
</people>   

这是一个只有几个名称标签的小xml文件,但由于ClassCastException错误,我甚至无法正确执行代码。对此有何看法?感谢工厂的帮助!

1 个答案:

答案 0 :(得分:0)

导入错误元素,应为org.w3c.dom.Element