如何以不同的RSS格式使用XmlNode.SelectSingleNode?

时间:2017-07-05 15:06:04

标签: c# xml rss

我从新闻网站RSS获取数据。我是从大约20个新闻网站获得的。但是,1个网站的RSS是不同的。 20 RSS使用相同的格式,但这个网站的RSS是不同的。如何在这个不同的RSS中搜索“入口”节点。我在互联网上搜索这种情况,但我找不到我想要的结果。你能帮助我吗 ?

这是RSS的正常格式

enter image description here

这是我的普通格式RSS代码

XmlDocument xdoc = new XmlDocument();

        xdoc.Load("http://www.milliyet.com.tr/rss/rssNew/gundemRss.xml");

        XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");

        if (el != null)
        {
            el.ParentNode.RemoveChild(el);
        }
        XmlNode Haberler = el.SelectSingleNode("channel");

        List<Milliyet> newMilliyet = new List<Milliyet>();


        foreach (XmlNode haber in Haberler.SelectNodes("item"))
        {
            var link = haber.SelectSingleNode("link").InnerText;

            if (MilliyetHaberList.ContainsKey(link))
                continue;

这是不同格式的RSS

enter image description here

1 个答案:

答案 0 :(得分:1)

你的错误是文件格式错误,这种方式不起作用,因为所有RSS链接都不是xml文件,有时rss链接返回应用程序/ rss + xml内容类型。

例如:NTV

NTV rss链接:http://www.ntv.com.tr/gundem.rss

如果您使用邮递员并获得此链接,您将看到内容类型:application / rss + xml

你应该像这样使用HttpRequest

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.ntv.com.tr/gundem.rss");
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        StreamReader stream = new StreamReader(response.GetResponseStream());

        string responseString = stream.ReadToEnd();

        string xmlString = responseString.Replace("xmlns=\"http://www.w3.org/2005/Atom\"", "");

        XmlDocument xdoc = new XmlDocument();

        xdoc.LoadXml(xmlString);

        var feedNode = xdoc.LastChild;

        XmlNodeList entries = feedNode.SelectNodes("entry");
        List<NTV> NTVNewsList = new List<NTV>();


        foreach (XmlNode entry in entries)
        {
            NTV NTVInstance = new NTV();
            foreach (XmlNode child in entry.ChildNodes)
            {
                string childName = child.Name;
                switch (childName)
                {
                    case "title":
                        NTVInstance.Title = child.InnerText;
                        break;
                    case "summary":
                        NTVInstance.Description = child.InnerText;
                        break;
                    case "published":
                        string dateStr = child.InnerText;
                        NTVInstance.PubDate = Convert.ToDateTime(dateStr);
                        break;
                    case "link":
                        NTVInstance.Link = child.Attributes["href"].Value;
                        NTVInstance.Tags = GetTags(NTVInstance.Link);

                        break;
                    default:
                        break;
                }

            }