4

您好我正在尝试在 Visual C# Express 中创建一个 RSS 阅读器。当表单加载时,我需要将 rss 提要读入文本框。我以前从未使用过 RSS 提要,我遇到的所有示例都是在 Visual Studio 中完成的,似乎我无法使用它:

       (XmlReader reader = XmlReader.Create(Url))

这就是我到目前为止所得到的。它不起作用。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var s = RssReader.Read("http://ph.news.yahoo.com/rss/philippines");
        textBox1.Text = s.ToString();
    }
    public class RssNews
    {
        public string Title;
        public string PublicationDate;
        public string Description;
    }

    public class RssReader
    {
        public static List<RssNews> Read(string url)
        {
            var webResponse = WebRequest.Create(url).GetResponse();
            if (webResponse == null)
                return null;
            var ds = new DataSet();
            ds.ReadXml(webResponse.GetResponseStream());

            var news = (from row in ds.Tables["item"].AsEnumerable()
                        select new RssNews
                        {
                            Title = row.Field<string>("title"),
                            PublicationDate = row.Field<string>("pubDate"),
                            Description = row.Field<string>("description")
                        }).ToList();
            return news;
        }
    }

我不确定我应该怎么做。请帮忙。

4

1 回答 1

2

好吧,您的代码按预期工作,因为您正在返回一个 RSSNews 项目列表,但是您以错误的方式将其分配给文本框。做textBox1.Text = s.ToString();会得到System.Collections.Generic.List....结果。

您的方法是从数据集中读取 RssNews 项目,并针对提要返回大约 23 个项目。您需要遍历这些项目并在文本框中显示其文本,或者如果您可以使用 GridView 或类似控件来显示这些结果则更好。

Main您可以在您的方法中尝试以下代码:

        var s = RssReader.Read("http://ph.news.yahoo.com/rss/philippines");
        StringBuilder sb = new StringBuilder();
        foreach (RssNews rs in s)
        {
            sb.AppendLine(rs.Title);
            sb.AppendLine(rs.PublicationDate);
            sb.AppendLine(rs.Description);
        }

        textBox1.Text = sb.ToString();

这将为 RssNews 的每个项目创建一个字符串,并将结果显示在 textBox1 中。

于 2012-06-25T04:47:40.683 回答