开发者

Subitems are not all added to a list view in C# using XmlNodeList

开发者 https://www.devze.com 2023-02-03 02:34 出处:网络
I\'m working on extracting data from an RSS feed. In my listview (rowNews), I\'ve got two columns: Title and URL. When the button is clicked, all of the titles of the articles are showing up in the ti

I'm working on extracting data from an RSS feed. In my listview (rowNews), I've got two columns: Title and URL. When the button is clicked, all of the titles of the articles are showing up in the title column, but only one URL is added to the URL column. I switched them around so that the URLs would be added to the first column and all of the correct URLs appeared... leading me to think this is a problem with my listview source (it's my fir开发者_JAVA技巧st time working with subitems). Here's the original, before I started experimenting with the order:

private void button1_Click(object sender, EventArgs e)
        {

            XmlTextReader rssReader = new XmlTextReader(txtUrl.Text);
            XmlDocument rssDoc = new XmlDocument();
            rssDoc.Load(rssReader);
            XmlNodeList titleList = rssDoc.GetElementsByTagName("title");
            XmlNodeList urlList = rssDoc.GetElementsByTagName("link");
            ListViewItem lvi = new ListViewItem();

             for (int i = 0; i < titleList.Count; i++)
             {
                 rowNews.Items.Add(titleList[i].InnerXml);
             }

             for (int i = 0; i < urlList.Count; i++)
             {
                 lvi.SubItems.Add(urlList[i].InnerXml);
             }

             rowNews.Items.Add(lvi);
        }


I think you should alter your code to something like this (untested)

         // ListViewItem lvi = new ListViewItem();

         for (int i = 0; i < titleList.Count; i++)
         {
            ListViewItem lvi = rowNews.Items.Add(titleList[i].InnerXml);
            lvi.SubItems.Add(urlList[i].InnerXml);
         }

         // rowNews.Items.Add(lvi);


Have you looked at working with the feed through the System.ServiceModel.Syndication namespace, the SyndicationFeed and SyndicationItem classes expose all the properties you are after and are easily bound to UI elements as POCO objects.

 using (XmlReader reader = XmlReader.Create(Settings.Default.ExchangeRateFeed))
        {
            SyndicationFeed feed = SyndicationFeed.Load(reader);

            if (feed != null)
            {
                foreach (var item in feed.Items)
                {
                    // Code to obtain required properties
                }
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号