1

現在、次のコードを使用して xml および 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;
    }
}

次に、を使用して JavaScript でこれを要求するとapplication/json; charset=utf-8、json データが自動的に取得されます。

私の問題は、ローカル データベースではなく外部 RSS フィードからデータを取得し、それを json データに変換して、javascript を使用して同じ方法で呼び出す必要があることです。

http://www.hotukdeals.com/rss/hot上記と同様のコードを使用して RSS フィードをキャプチャする方法を知っている人はいますか?

4

2 に答える 2

6

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;
    }

上記の Deal クラスをアプリに必要なクラスに置き換え、エラー処理も追加します :)

詳細については、 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);
        }

この記事で見つけました: SyndicationFeed を使用して SyndicationItem の非標準要素を読み取る

于 2012-07-09T22:01:30.667 に答える
0

Web フィードは、頻繁に更新されるコンテンツをユーザーに提供するために使用されるデータ形式です。Web サイトのホームページをデザインしていて、人気のある Web サイトや有用な Web サイトからのフィードを表示したいとします。この場合、次の例が役立つ場合があります。

この例では、消費されたフィードがリストビューに表示されます。ただし、任意のコントロールを使用して、それに応じてフィードを表示できます。

リストビューのスクリプトは次のとおりです。

<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();
    }
}

注: 他の Web サイトから取得したデータには常に注意を払う必要があります。

于 2012-07-11T07:13:05.843 に答える