铸造节点元素给ClassCastException异常(Casting node to elemen

2019-06-26 18:31发布

这里N2是我的节点列表,我只是想看看我的根元素的第一个子节点

public void ClickMe(View view){


    Node rootElement=n2.item(0);
    NodeList child=rootElement.getChildNodes();

    Node first=child.item(0);
    //ClassCastException error is coming whenever i am casting first to Element.

    Element nm=(Element)first;

    Option q= getOption(nm,first);
    Log.i(TAG,"the name is was talking about is : "+ q.getName());
}

这是什么logcat的说

07-31 20:32:38.376: E/AndroidRuntime(2950): Caused by: java.lang.ClassCastException: org.apache.harmony.xml.dom.TextImpl cannot be cast to org.w3c.dom.Element

Answer 1:

尝试像这样....

NodeList LOP = odoc.getElementsByTagName("Your_XML_Top_Element");

                Node FPN =LOP.item(0);
                try{
                if(FPN.getNodeType() == Node.ELEMENT_NODE)
                    {

                    Element token = (Element)FPN;

                    NodeList oNameList1 = token.getElementsByTagName("Your_XML_Sub_Node");
                    Element firstNameElement = (Element)oNameList1.item(0);
                    NodeList textNList1 = firstNameElement.getChildNodes();

}


Answer 2:

如果节点是元素,则仅投放。 请检查像下面。

if (first.getNodeType() == Node.ELEMENT_NODE) { Element nm=(Element)first;}


文章来源: Casting node to element giving ClassCastException