So im trying to parse and xml file in android. Bellow is a link to the file and my code. I’m trying to get the current temp stored as “temp_f” in the “current_conditions” element. But every time i run it i get this error, 09-15 20:26:47.359: DEBUG/ErOr(17663): java.lang.ClassCastException: org.apache.harmony.xml.dom.ElementImpl
http://www.google.com/ig/api?weather=10598
DocumentBuilderFactory factory1 = DocumentBuilderFactory.newInstance();
factory1.setNamespaceAware(true); // never forget this!
InputSource source = new InputSource(new StringReader(xmltemp));
Document doc = factory1.newDocumentBuilder().parse(source);
String newstring = "" + ((DocumentBuilderFactory) ((Document) doc.getDocumentElement().
getElementsByTagName("current_conditions").item(0)).
getElementsByTagName("temp_f").item(0)).
getAttribute("data");
Have a look at the Java XPath API — that should be much nicer than traversing the DOM to find your data:
As for the original question:
First put every statement of your extraction code on a line of its own, this will help you a lot with finding the problems (and line numbers in stacktrace will be a lot more precise):
At
/*1*/you try to cast aorg.w3.dom.Nodeinto anorg.w3.dom.Document— but not everyNodeis aDocument, as can be seen by theClassCastExceptionhere: The returnedNodeis actually an instance of theorg.w3.dom.Elementinterface, more precisely an instance of class oforg.apache.harmony.xml.dom.ElementImpl(part of the Apache Harmony XML parser implementation).So let’s remove the cast and change the declared type of
curr_condtoNode:Now a second problem becomes obvious at
/*2*/: TheNodeinterface does not specify agetElementsByTagName()method, that’s probably why you did try to cast toDocumentabove. This won’t compile and there is no way to get it to.Why you cast the result to
DocumentBuilderFactoryis beyond me. Yes, there is agetAttribute()method but both the class name and method javadoc should have made clear that it’s definitely not doing want you want.So my above recommendation holds: Please use XPath, it’s the better tool for this task 🙂
There actually is a way to extract the data using only DOM for your first task (current temperature). It relies on the fact that the
temp_felement is unique and is a lot more verbose than the above XPath expression, though: