2012-07-05 3 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; 
    } 
} 

그때, 나는 자동으로 JSON 데이터를 얻을 수 application/json; charset=utf-8를 사용하여 자바 스크립트에서이 요청하는 경우.

내 문제는 외부 RSS 피드에서 로컬 데이터베이스 대신 데이터를 가져와 json 데이터로 변환해야하므로 자바 스크립트를 사용하여 같은 방식으로 호출 할 수 있습니다.

아무도 내가 위의 비슷한 코드를 사용하여 http://www.hotukdeals.com/rss/hot RSS 피드를 캡처 할 수있는 방법을 알고 계십니까?

+1

RSS 피드를 읽어야 할 필요가 있습니다. 2. RSS 구조를 원하는 JSON 구조로 변환하십시오. 3.이 코드를 웹 서비스에 넣으십시오. 4. 결과를 캐싱하거나 캐시하도록 설정하십시오. RSS 데이터 읽기. 특히 어려워 보이지 않습니다 -이 부분에서 어떤 부분을 고집하고 있습니까? 또는 데이터베이스에서 데이터를 제공하는 것이 더 행복하다면 RSS 데이터를 가져 와서 데이터베이스에 추가하는 작업을 작성할 수 있으므로이를 제공 할 수 있습니다. 그러면 JSON 피드의 레코드 수를 제어 할 수 있습니다. – Rup

+0

위의 코드에서 json으로 SQL을 자동 변환하는 것과 비슷한 rss에서 json으로의 변환이 자동으로 수행되지 않아야합니까? 기본적으로 위 코드에서 동일한 개념을 사용하려고하지만 데이터베이스의 데이터를 가져 오지 않고 대신 RSS 피드를 사용합니다. – oshirowanen

+2

그 코드는 자동으로 SQL로부터 변환되지 않고, 데이터베이스에서 읽은'App' 구조체 목록에서 변환됩니다. 유사한 구조로 RSS 데이터를 읽으면 JSON이 자동으로 출력되지만 예 - 여전히 자신의 데이터를 읽어야합니다. – Rup

답변

5

System.ServiceModel.Web에에 refrence를 추가하고 다음 코드를 사용합니다

[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 설명서를 확인하십시오.


는이 글에서 그것을 발견

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

하는 dc:date 속성을 읽어

using System.Xml.Linq; 

을 추가 한 다음 (첫 번째 날짜 변환)를 foreach 루프에서이 작업을 추가하려면 : Reading non-standard elements in a SyndicationItem with SyndicationFeed

+0

'Using System .ServiceModel.Web; "맨 위에 있지만 Visual Studio의 Intellisense를 통해 XmlReader를 옵션으로 가져 오지 못합니다. 그런 다음이를 무시하고 코드에 비슷한 코드를 사용하면 '유형 또는 네임 스페이스 이름'XmlReader '를 찾을 수 없습니다 (사용 지시문이나 어셈블리 참조가 누락 되었습니까?)'라는 메시지가 표시됩니다. – oshirowanen

+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/library/system.servicemodel.syndication.syndicationfeed.aspx); System.Xml 및 System.ServiceModel (.NET 4의 경우 System.ServiceModel.Web .NET 3.5의 경우)에 각각 참조를 추가해야합니다. 레퍼런스 란 프로젝트의 References 폴더를 오른쪽 클릭하는 것입니다.'using '도 필요하지만 어셈블리 레퍼런스가 먼저 필요합니다. – Rup

+0

거의 작동하는 것 같습니다. 'item.Title.Text'는 작동하지만 다른 피드의 다른 요소 인'Link'가 있습니다. 그래서'item.Link.Text'를 시도 할 때, 오류 메시지가 나타납니다.'CS1061 : 'System.ServiceModel.Syndication.SyndicationItem'은 'Link'에 대한 정의를 포함하지 않고 첫 번째 인수를 허용하는 'Link'확장 메서드가 없습니다. 'System.ServiceModel.Syndication.SyndicationItem'타입을 찾을 수 있습니다 (사용 지시문이나 어셈블리 참조가 누락 되었습니까?) ' – oshirowanen

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

참고 : 우리는 항상 우리가 다른 웹 사이트에서 얻을 데이터에 대한 관심을 가져야.

관련 문제