Ottenere NodeList dal documento XML
-
26-10-2019 - |
Domanda
Ho sviluppato la seguente classe per recuperare il nodo-list di un documento XML:
public class XMLDownloader {
public static NodeList getNodeList(){
String url = "http://localhost/xml/example.xml";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
NodeList result = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
result = doc.getElementsByTagName("client");
is.close();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
}
Ma questo metodo restituisce null
. Tutte le idee?
Il file xml:
<status>
<client type="s" name="test1" protocol="1000">
</client>
<client type="r" name="test2" protocol="2000">
</client>
<client type="r" name="test3" protocol="3000">
</client>
<client type="h" name="test4" protocol="4000">
</client>
<client type="c" name="test5" protocol="5000">
</client>
</status>
Soluzione
Il codice scritto in questione in realtà funziona per me senza errori. Ho un NodeList contenente gli attesi 5 elementi. Ho provato su un emulatore in esecuzione 2.2.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow