using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml.Xsl;
using System.Xml;

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

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";//输出类型
            XDocument rss = null;//创建XDocument类型的rss变量
            try
            {
                //从URL参数中获取目标RSS源的路径
                string rssUrl = context.Server.UrlDecode(context.Request.QueryString["url"]);
                rss = XDocument.Load(rssUrl);//读取RSS
                //遍历所有的item节点下的pubDate（发布日期）节点，将其转为自己喜欢的时间格式，如yyyy年MM月dd HH:mm
                foreach (var item in rss.Root.Element("channel").Elements("item"))
                {
                    item.Element("pubDate").Value = Convert.ToDateTime(item.Element("pubDate").Value).ToString("yyyy年MM月dd HH:mm");
                }
            }
            catch
            {
                context.Response.Write("RSS URL错误，或RSS源格式错误！");//读取错误
                return;
            }
            XDocument formattedRss = new XDocument();//定义一个新的XDocument变量，用于储存格式转换后的RSS信息
            using (XmlWriter writer = formattedRss.CreateWriter())
            {
                XslCompiledTransform xslt = new XslCompiledTransform();
                XmlReader xsltReader = (XmlReader.Create("RssXslt.xslt"));//定义XmlReader读取器
                xslt.Load(xsltReader); //载入RssXslt.xslt
                //将格式化后的结果写入writer中（由formattedRss.CreateWriter()创建）
                xslt.Transform(rss.CreateReader(), writer);
                xsltReader.Close();//关闭xsltReader
            }
            context.Response.Write(formattedRss.ToString());//输出formattedRss内容
        }

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