2012-07-05 70 views
0

目前,我使用下面的代码生成XML和JSON数据:如何获取.net 3.5自动生成基于RSS订阅源的JSON数据?

public class App 
{ 
    public string app_name; 
    public string app_path; 

    public App(string m_app_name, string m_app_path) 
    { 
     app_name = m_app_name; 
     app_path = m_app_path; 
    } 

    public App() { } 
} 

[ScriptService] 
public class Apps : WebService { 
    List<App> App = new List<App>(); 

    SqlConnection connection; 
    SqlCommand command; 
    SqlDataReader reader; 

    [WebMethod()] 
    public List<App> GetUserApps() 
    { 
     var apps = new List<App>(); 

     using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"])) 
     { 


       using (command = new SqlCommand(@"some query here", connection)) 
       { 
        connection.Open(); 
        using (reader = command.ExecuteReader()) 
        { 
         int AppNameIndex = reader.GetOrdinal("application_name"); 
         int AppPathIndex = reader.GetOrdinal("application_path"); 

         while (reader.Read()) 
         { 
          apps.Add(new App(reader.GetString(AppNameIndex), reader.GetString(AppPathIndex))); 
         } 
        } 
       } 



     } 

     return apps; 
    } 
} 

如果我再使用application/json; charset=utf-8,我自动获得JSON数据请求这个在JavaScript。

我的问题是,我需要从外部RSS提要获取数据,而不是本地数据库,并将其转换为json数据,以便我可以使用JavaScript以相同的方式调用它。

任何人都知道如何使用上面类似的代码捕获RSS提要http://www.hotukdeals.com/rss/hot

+1

所以我想你需要1.阅读你的RSS提要2.将RSS结构转换为你想要的JSON结构3.把这段代码放入一个Web服务4.设置它缓存结果或缓存RSS数据读取。这听起来不是特别困难 - 你坚持的是哪一部分?或者,如果您更乐意从数据库中提供数据,那么您总是可以写一份工作来获取您的RSS数据并将其添加到数据库中,然后您可以将其提供。这也可以让你控制你的JSON提要中的记录数量。 – Rup 2012-07-09 10:04:25

+0

不应该从rss到json的转换自动发生,类似于我自动将上述代码中的sql转换为json的方式吗?基本上,我想在上面的代码中使用相同的概念,但是从获取数据库中的数据并改为使用rss提要进行更改。 – oshirowanen 2012-07-09 10:07:07

+2

该代码不会自动从SQL转换,而是从您从数据库中读取的'App'结构列表转换而来。将你的RSS数据读入类似的结构,它会自动输出JSON,是的 - 但你仍然需要自己读取数据。 – Rup 2012-07-09 10:09:17

回答

5

添加refrence到System.ServiceModel.Web和使用下面的代码:

[WebMethod()]  
    public List<Deal> GetDeals() 
    { 
     var deals = new List<Deal>(); 

     XmlReader xr = XmlReader.Create("http://www.hotukdeals.com/rss/hot"); 
     SyndicationFeed feed = SyndicationFeed.Load(xr); 

     foreach (var item in feed.Items) 
     { 
      deals.Add(new Deal { Title = item.Title.Text, Summary = item.Summary.Text }); 
     } 

     return deals; 
    } 

替换上面你需要为你的应用程序不论类交易类,并添加一些错误处理,以及:)

查看SyndicationFeed文档了解详情。


要读取dc:date属性,添加

using System.Xml.Linq; 

,然后在foreach循环中添加这个(将第一日期)

 var dates = item.ElementExtensions.Where(x => x.OuterName == "date"); 

     if(dates.Count() > 0) 
     { 
      var element = dates.First().GetObject<XElement>(); 
      var d = DateTime.Parse(element.Value); 
     } 

我发现它在这篇文章中:Reading non-standard elements in a SyndicationItem with SyndicationFeed

+0

我已经添加了'使用系统.ServiceModel.Web;'顶部,但我没有通过Visual Studio的Intellisense获得XmlReader作为选项。如果我然后忽略它并在你的代码中使用类似的代码,我会得到一个错误'无法找到类型或名称空间名'XmlReader'(你是否缺少using指令或程序集引用?)' – oshirowanen 2012-07-10 08:38:13

+1

XmlReader应该在[ System.Xml](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx)和SyndicationFeed在[System.ServiceModel.Syndication](http://msdn.microsoft.com/ EN-US /库/ system.servicemodel.syndication.syndicationfeed.aspx);您需要分别添加对System.Xml和System.ServiceModel的引用(.NET 4; System.ServiceModel.Web for .NET 3.5)。通过引用我的意思是右键单击项目中的References文件夹 - 您也需要使用's,但您首先需要使用组件引用。 – Rup 2012-07-10 08:42:21

+0

它几乎似乎在工作。 'item.Title.Text'可以工作,但我在另一个Feed中有另一个元素,它是'Link'。所以当我尝试'item.Link.Text'时,我收到一条错误消息:'CS1061:'System.ServiceModel.Syndication.SyndicationItem'没有包含'Link'的定义,也没有接受第一个参数的扩展方法'Link'可以找到'System.ServiceModel.Syndication.SyndicationItem'类型(你是否缺少using指令或程序集引用?)' – oshirowanen 2012-07-10 09:05:00

0

网络订阅源是一种数据格式,用于为用户提供频繁更新的内容。假设您正在设计任何网站的主页,并且想要显示来自某个流行或有用网站的供稿。在这种情况下,以下示例可能会有所帮助。

在此示例中,所消耗的提要显示在列表视图中。但是您可以使用任何控件并相应地显示提要。

的脚本列表视图是:

<div> 
    <asp:ListView ID="FeedList" runat="server" 
      onitemdatabound="FeedList_ItemDataBound" DataKeyNames="Title,Link" > 
     <LayoutTemplate > 
      <div runat="server" id="ItemPlaceHolder"> 
      </div> 
     </LayoutTemplate> 
     <ItemTemplate> 
      <asp:Label ID="title" runat="server"></asp:Label> 
      <br /> 
      <asp:HyperLink ID="link" runat="server"></asp:HyperLink> 
      <br /> 
     </ItemTemplate> 
    </asp:ListView> 
</div> 

隐藏文件的例子的代码是:

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Xml; 
using System.Data; 
using System.ServiceModel.Syndication; // used for feed implementation 

public partial class FeedConsume : System.Web.UI.Page 
{ 
    /// <summary> 
    /// databind function of listview is called from this function. 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     // See if feed data is in the cache 
     IEnumerable<SyndicationItem> items = Cache["Feeds"] as IEnumerable<SyndicationItem>; 
     if (items == null) 
     { 
      // If not present in cache then get it from sender's website 
      try 
      { 
       SyndicationFeed sfFeed = SyndicationFeed.Load(XmlReader.Create("FEED URL OF senders website")); 

       // every website has a static url which contains their feed and we can get the feed from that url. 
       items = sfFeed.Items; 
       } 
      catch 
      { 
       items = new List<SyndicationItem>(); 
      } 
      // Add the items to the cache 
      Cache.Insert("Feeds", items, null, DateTime.Now.AddHours(1.0),TimeSpan.Zero); 
     } 

     // Creating the datatable to bind it to the listview. This datatable will contain all the feeds from the senders website. 
     DataTable dtItems = new DataTable(); 
     dtItems.Columns.Add("Title", typeof(string)); 
     dtItems.Columns.Add("Link", typeof(string)); 
     foreach (SyndicationItem synItem in items) 
     { 
      dtItems.Rows.Add(synItem.Title.Text, synItem.Links[0].Uri.ToString()); 
     } 
     FeedList.DataSource = dtItems; 
     FeedList.DataBind(); 
    } 

    /// <summary> 
    /// Controls in listView are assigned proper value 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    protected void FeedList_ItemDataBound(object sender, ListViewItemEventArgs e) 
    { 
     ListViewDataItem lvDataItem = (ListViewDataItem)e.Item; 
     DataRowView drvItem = (DataRowView)lvDataItem.DataItem; 
     Label title = (Label)e.Item.FindControl("title"); 
     title.Text = drvItem["Title"].ToString(); 
     HyperLink link = (HyperLink)e.Item.FindControl("link"); 
     link.Text = drvItem["Link"].ToString(); 
     link.NavigateUrl = drvItem["Link"].ToString(); 
    } 
} 

注:我们要始终关心我们从其他网站获取的数据。