using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;

namespace BookDemo.RSS
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Rss : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //读取数据 PS：可以为任意类型的数据源
            XDocument datasource = XDocument.Load("Datasource.xml");
            //获取数据
            List<Article> articleList = datasource.Root.Elements("Article")
                           .OrderByDescending(a => Convert.ToInt32(a.Element("ID").Value))
                           .Take(10)
                           .Select(a => new Article()
                           {
                              ID = Convert.ToInt32(a.Element("ID").Value),
                               Title = a.Element("Title").Value,
                               Description = a.Element("Description").Value,
                               Text = a.Element("Text").Value,
                               CreateTime = Convert.ToDateTime(a.Element("CreateTime").Value)
                           }).ToList();

            //专成RSS标准格式的XML
            XDocument rss = new XDocument();
            //设置根节点<rss>
            XElement rootElement = new XElement("rss");
            rootElement.SetAttributeValue("version", "2.0");
            //设置<channel>节点
            XElement channelElement = new XElement("channel");
            //设置<channel>节点基本信息
            channelElement.Add(
                new XElement("title", "BookDemo.RSS 测试 RSS"),
                new XElement("link", "http://localhost:2322"),
                new XElement("description", "This is an example for RSS"),
                new XElement("language", "en-us"));

            //创建<item>节点
            foreach (var item in articleList)
            {
                channelElement.Add(new XElement("item",
                       new XElement("title", item.Title),
                       new XElement("link", "ArticleDetail.aspx?id=" + item.ID),
                       new XElement("description", item.Description)));
            }
            //添加节点
            rootElement.Add(channelElement);
            rss.Add(rootElement);

            context.Response.ContentType = "text/xml";//输出xml格式
            context.Response.Write(rss.ToString());//输出带缩进格式的XML
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
