我不知道为什么,但是 Log.i(TAG, "found: "+found);为我在流中获取的 XML 中的“找到”元素返回 null。我调试过,似乎我的 XML 根元素已被读取,但该根元素的元素未被读取。 urlString 也是正确的。文档被解析,没有任何错误和异常。但是在这行
NodeList nl = docEle.getElementsByTagName("found");
found = nl.item(0).getNodeValue();
发现是空的。这是方法的完整代码:
protected Void doInBackground(String... urls) {
String urlString = urls[0];
URL documentUrl = null;
InputStream stream = null;
URLConnection conn = null;
DocumentBuilder builder = null;
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
documentUrl = new URL(urlString);
conn = documentUrl.openConnection();
stream = conn.getInputStream();
document = builder.parse(stream);
}
catch (IOException e) {
Error = e.getMessage();
Log.i(TAG, "Exception!", e);
}
catch (SAXException e) {
Error = e.getMessage();
Log.i(TAG, "Exception!", e);
}
catch (ParserConfigurationException e) {
Error = e.getMessage();
Log.i(TAG, "Exception!", e);
}
finally
{
if (stream != null)
{
try {
stream.close();
} catch (IOException e) {
Error = e.getMessage();
Log.i(TAG, "Exception!", e);
}
}
}
/*NodeList nodes = document.getElementsByTagName("found");
for (int i = 0; i < nodes.getLength(); i++) {
found = nodes.item(i).getNodeValue();
//System.out.println(found);
Log.i(TAG, "found: "+found);
}*/
//get the root element
Element docEle = document.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("found");
found = nl.item(0).getNodeValue();
Log.i(TAG, "found: "+found);
return null;
}
这是我的带有 XML 的 urlString:http://basa.med-info.ru/xse/index.php?query=%E3%F0%E8%EF%EF&nres=20
found 必须等于 20。
最佳答案
使用:
found = nl.item(0).getFirstChild().getNodeValue();
关于java - 在 Android 中解析 XML 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9360425/