java - 如何从RSS中获取数据?

标签 java android xml xml-parsing rss

我无法从 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/

相关文章:

android - 为支持库首选项设置默认值时出现 ClassCastException

xml - Kotlin:格式化字符串

java - 无法连接到服务器,getResponseCode() 返回-1

java - 使用桌面作为清晰的白板

java - 读取文件并将数据存储在数组中,然后找到最小的十进制值

java - Android程序写入模拟器而不是手机

用于 GUI 的 Java 2D 场景图形库

android - setOnItemClickListener NOT WORKING 和 setOnItemLongClickListener 在 ListView 中工作

xml - 捕获不是其他节点的后代的节点,当前上下文除外

"Any number of these elements - in any order"的 XML 架构构造