我无法从 rss 获取数据...空异常 我从此link检索,它只有
<?xml version="1.0" encoding="utf-8"?>
<GoldQuotes>
<Price Date="2013-11-28 09:22" Value="1244.30" />
<Price Date="2013-11-28 09:20" Value="1243.10"/>
<Price Date="2013-11-28 09:18" Value="1243.30"/>
[...]
</GoldQuotes>
这是我的java fragment 代码
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("GoldQuotes"); //***
if ((nl != null) && (nl.getLength() > 0)) {
for (int i = 0; i < nl.getLength(); i++) {
dissectNode(nl, i);
}
}//if
[...]
public void dissectNode(NodeList nl, int i) {
try {
Element entry = (Element) nl.item(i);
Element price = (Element) entry.getElementsByTagName("Price").item(0);
String priceValue = price.getAttribute("Value"); //get gold value
SingleNewsItem singleItem = new SingleNewsItem(priceValue);
newsList.add(singleItem);
} catch (DOMException e) {
e.printStackTrace();
}
}// dissectNode
在执行NodeList nl = docEle.getElementsByTagName("GoldQuotes")
之后。我用 nl.getLength()
进行测试,它返回 0..
我错过了什么吗?
最佳答案
您尝试解析的文档不是 rss,只是自定义的 xml 格式。解析之后,像这样修改我们的代码就足够了:
// this returns the root element, ie "GoldQuotes"
Element docEle = dom.getDocumentElement();
// get the list of Price elements children of the root
NodeList nl = docEle.getElementsByTagName("Price");
if ((nl != null) && (nl.getLength() > 0)) {
for (int i = 0; i < nl.getLength(); i++) {
// get the i-th Price element from the nodelist
Element entry = (Element) nl.item(i);
// get its Value attribute
String priceValue = entry.getAttribute("Value");
[....]
}
}
关于java - 如何从RSS中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20261863/