Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting node to element giving ClassCastException

here n2 is my NodeList, and i just want to see the first child node of my root element

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

this what logcat says

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
like image 307
nam_ph Avatar asked Aug 06 '12 04:08

nam_ph


2 Answers

Try it like this....

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

}
like image 91
Kumar Vivek Mitra Avatar answered Oct 19 '22 01:10

Kumar Vivek Mitra


If node is element then only cast it. Make check like below.

if (first.getNodeType() == Node.ELEMENT_NODE) { Element nm=(Element)first;}
like image 38
kosa Avatar answered Oct 19 '22 00:10

kosa