I’m VERY new to Java, so I’m hoping this is an easy question.
I’m trying to read in and parse an XML file. I’ve followed a few tutorials, and all of them show this line (with varying variable names, but – same concept):
Element eElement = (Element) nNode;
As soon as I get to this line, and run it, my app crashes. I believe it’s supposed to take the node item and convert it to an element:
System.out.println("Root element :" + myDoc.getDocumentElement().getNodeName());
NodeList nList = myDoc.getElementsByTagName("title");
System.out.println("----------------------");
for(int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if(nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
}
}
LogCat:
05-03 02:12:20.865: I/System.out(9424): Root element :rss
05-03 02:12:20.865: I/System.out(9424): ----------------------
05-03 02:12:20.875: W/System.err(9424): java.lang.ClassCastException: org.apache.harmony.xml.dom.ElementImpl
05-03 02:12:20.875: W/System.err(9424): at com.sltrib.test.Main.onCreate(Main.java:68)
05-03 02:12:20.875: W/System.err(9424): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-03 02:12:20.875: W/System.err(9424): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
05-03 02:12:20.875: W/System.err(9424): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
05-03 02:12:20.875: W/System.err(9424): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
05-03 02:12:20.875: W/System.err(9424): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
05-03 02:12:20.875: W/System.err(9424): at android.os.Handler.dispatchMessage(Handler.java:99)
05-03 02:12:20.875: W/System.err(9424): at android.os.Looper.loop(Looper.java:123)
05-03 02:12:20.875: W/System.err(9424): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-03 02:12:20.875: W/System.err(9424): at java.lang.reflect.Method.invokeNative(Native Method)
05-03 02:12:20.875: W/System.err(9424): at java.lang.reflect.Method.invoke(Method.java:507)
05-03 02:12:20.875: W/System.err(9424): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-03 02:12:20.875: W/System.err(9424): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-03 02:12:20.875: W/System.err(9424): at dalvik.system.NativeStart.main(Native Method)
I would guess that you imported an Element class, but from a different package (i.e. not
org.w3c.dom.Element, but another class named Element in another package).Check your import statements.
Note that the instruction causing the exception is a cast. It doesn’t convert the casted object. Instead, it takes a reference to an object of type Node and make it a reference of type Element. The casted object is unaffected by this operation. And the operation can succeed only if the object is indeed of type Element.