Java 读取 RSS,顺便还有xpath的用法

本文介绍了使用Java读取RSS源的具体方法,并通过示例展示了如何解析XML文件中的特定节点。此外,还提供了使用XPath表达式进行精确查询的例子,并展示了Yahoo Weather RSS响应的结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java读取RSS:
  1. //http://zfive.blogbus.com/logs/20959998.html

  2. package com.yourcompany.struts.user;
  3. import java.io.IOException;
  4. import java.io.File;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import javax.xml.parsers.DocumentBuilder;
  8. import javax.xml.parsers.DocumentBuilderFactory;
  9. import javax.xml.parsers.ParserConfigurationException;

  10. import org.w3c.dom.Document;
  11. import org.w3c.dom.Element;
  12. import org.w3c.dom.Node;
  13. import org.w3c.dom.NodeList;
  14. import org.xml.sax.SAXException;
  15. import java.net.URL;

  16. public class Test {
  17.  public static void main(String[] args) {
  18.   try{
  19.    List result = new ArrayList();  //声明一个结果集
  20.    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //解析器工厂类
  21.    DocumentBuilder db;
  22.    Document doc;
  23.   
  24.    //此DocumentBuilder对象的作用是根据xml文件的url地址生成document对象
  25.    db =dbf.newDocumentBuilder();     //得到一个DOM解析器对象;
  26.     //File file = new File("students.xml"); //当然,我们也可以读出本地计算机中的xml文档
  27.   
  28.    //doc对象包含需要解析的feed的xml文件
  29.    URL file = new URL("http://localhost:8080/rSS/pfocus.xml");
  30.    
  31.    doc = db.parse(file.openStream());  //把解析后的XML,赋给文档对象; 
  32.    //feed的xml文件的组成单位是item,从doc中取出所有的item
  33.    NodeList nl = doc.getElementsByTagName("item");  //多个<item>标签组成一个链表;
  34.  
  35.    for(int i=0;i<nl.getLength();i++)
  36.    {
  37.     Element eltStu = (Element)nl.item(i);

  38.     //此处得到元素中的<title></title>标签实体;
  39.     Node titlenode = eltStu.getElementsByTagName("title").item(0);  

  40.     //返回第一个节点的值;

  41.       String title = titlenode.getFirstChild().getNodeValue();
  42.     
  43.     Node linknode = eltStu.getElementsByTagName("link").item(0);
  44.     String link = linknode.getFirstChild().getNodeValue();
  45.     
  46.     Node descriptionnode = eltStu.getElementsByTagName("description").item(0);
  47.     String description = descriptionnode.getFirstChild().getNodeValue();
  48.     
  49.     Node authornode = eltStu.getElementsByTagName("author").item(0);
  50.     String author = authornode.getFirstChild().getNodeValue();
  51.     
  52.     
  53.     System.out.println(title);
  54.     System.out.println(author);
  55.     System.out.println(link);
  56.     System.out.println(description);
  57.     System.out.println("---------");
  58.       }
  59.   }
  60.    catch(ParserConfigurationException e)
  61.    {
  62.     e.printStackTrace();
  63.    }catch(SAXException e){
  64.     e.printStackTrace();
  65.    }catch(IOException e){
  66.     e.printStackTrace();
  67.    }finally{
  68.    }

  69. }

  70. }
然后是xpath的部分:
 import java.io.IOException;
 4 
 5 import javax.xml.parsers.*;
 6 import javax.xml.xpath.*;
 7 
 8 import org.w3c.dom.*;
 9 import org.xml.sax.SAXException;
10 
11 class XpathSample {
12     public static void main(String[] args) throws ParserConfigurationException,
13             SAXException, IOException, XPathExpressionException {
14         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
15         factory.setNamespaceAware(true);
16         DocumentBuilder builder = factory.newDocumentBuilder();
17         Document doc = builder.parse("XmlFile/books.xml");
18         XPathFactory xFactory = XPathFactory.newInstance();
19         XPath xpath = xFactory.newXPath();
20         XPathExpression expr = xpath
21                 .compile("//book[author='Neal Stephenson']/price/text()");
22         Object result = expr.evaluate(doc, XPathConstants.NODESET);
23         NodeList nodes = (NodeList) result;
24         for (int i = 0; i < nodes.getLength(); i++) {
25             System.out.println(nodes.item(i).getNodeValue());
26         }
27     }
28 
29 }

大概就是这样了。对啦对啦,还有yahoo的weather格式:

首先了解Yahoo Weather Api的RSS Response格式:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="<a href="http://xml.weather.yahoo.com/ns/rss/1.0">http://xml.weather.yahoo.com/ns/rss/1.0</a>" xmlns:geo="<a href="http://www.w3.org/2003/01/geo/wgs84_pos">http://www.w3.org/2003/01/geo/wgs84_pos</a>#">
  <channel>
    <title>Yahoo! Weather - Tangshan, CH</title>
    <link>http://us.rd.yahoo.com/dailynews/rss/weather/Tangshan__CH/*http://weather.yahoo.com/forecast/CHXX0131_f.html</link>
    <description>Yahoo! Weather for Tangshan, CH</description>
    <language>en-us</language>
    <lastBuildDate>Fri, 22 Aug 2008 8:00 am CST</lastBuildDate>
    <ttl>60</ttl>
    <yweather:location city="Tangshan" region=""   country="CH"/>
    <yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
    <yweather:wind chill="67"   direction="290"   speed="4" />
    <yweather:atmosphere humidity="95"  visibility="4.97"  pressure=""  rising="0" />
    <yweather:astronomy sunrise="5:26 am"   sunset="6:54 pm"/>
    <image>
      <title>Yahoo! Weather</title>
      <width>142</width>
      <height>18</height>
      <link>http://weather.yahoo.com</link>
      <url>http://l.yimg.com/us.yimg.com/i/us/nws/th/main_142b.gif</url>
    </image>
    <item>
      <title>Conditions for Tangshan, CH at 8:00 am CST</title>
      <geo:lat>39.63</geo:lat>
      <geo:long>118.17</geo:long>
      <link>http://us.rd.yahoo.com/dailynews/rss/weather/Tangshan__CH/*http://weather.yahoo.com/forecast/CHXX0131_f.html</link>
      <pubDate>Fri, 22 Aug 2008 8:00 am CST</pubDate>
      <yweather:condition  text="Mostly Cloudy"  code="28"  temp="67"  date="Fri, 22 Aug 2008 8:00 am CST" />
      <description>
        <![CDATA[
<img src="<a href="http://l.yimg.com/us.yimg.com/i/us/we/52/28.gif"/><br">http://l.yimg.com/us.yimg.com/i/us/we/52/28.gif"/><br</a> />
<b>Current Conditions:</b><br />
Mostly Cloudy, 67 F<BR />
<BR /><b>Forecast:</b><BR />
Fri - Partly Cloudy. High: 86 Low: 69<br />
Sat - Partly Cloudy. High: 88 Low: 70<br />
<br />
<a href="<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Tangshan__CH/*http://weather.yahoo.com/forecast/CHXX0131_f.html">Full">http://us.rd.yahoo.com/dailynews/rss/weather/Tangshan__CH/*http://weather.yahoo.com/forecast/CHXX0131_f.html">Full</a> Forecast at Yahoo! Weather</a><BR/>
(provided by The Weather Channel)<br/>
]]>
      </description>
      <yweather:forecast day="Fri" date="22 Aug 2008" low="69" high="86" text="Partly Cloudy" code="30" />
      <yweather:forecast day="Sat" date="23 Aug 2008" low="70" high="88" text="Partly Cloudy" code="30" />
      <guid isPermaLink="false">CHXX0131_2008_08_22_8_00_CST</guid>
    </item>
  </channel>
</rss>

我们所需要用到的Node是//rss/channel/item/yweather:forecast


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值