Reputation: 43
I'm having a little trouble parsing a string of xml called responseText in android. The xml is fully valid and has the following structure:
<plan>
<entry>
<name>john</name>
<address>uk</address>
</entry>
<entry>
<name>joe</name>
<address>usa</address>
</entry>
</plan>
The code I am using to parse the String is as follows:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(responseText));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("entry");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = ((Document) element)
.getElementsByTagName("name");
Element line = (Element) name.item(0);
Toast.makeText(Containers.this,
getCharacterDataFromElement(line), Toast.LENGTH_SHORT)
.show();
NodeList title = ((Document) element)
.getElementsByTagName("address");
line = (Element) title.item(0);
Toast.makeText(Containers.this,
getCharacterDataFromElement(line), Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = ((Node) e).getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
I'm just using simple toasts to print the xml data to screen. However, i get an IOexception when I enter the for loop. Any idea what is wrong?
Upvotes: 0
Views: 3314
Reputation: 516
Are you importing the types from the correct packages? Something like
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.sax.Element; // Wrong Element class
Change the last import to
import org.w3c.dom.Element;
and try again.
Upvotes: 8
Reputation: 65126
I don't see anything that could cause an IOException inside the loop.
However, are you sure you can just go and cast an Element into a Document? At any rate you shouldn't need to anyways, since Element also has the getElementsByTagName method.
Upvotes: 1