0

I am trying to parse this xml file http://feeds.bbci.co.uk/news/world/rss.xml into a ListBox in visual C#, I tried a lot of different methods none of them worked, this is the one that kind of works:

XElement element = XElement.Load("http://feeds.bbci.co.uk/news/world/rss.xml");
foreach (XElement item in element.Elements("channel")) {
   listBox1.Items.Add(item.Value);
}

the only problem is, it loads the wrong object and if I set it to

XElement element = XElement.Load("http://feeds.bbci.co.uk/news/world/rss.xml");
foreach (XElement item in element.Elements("item")) {
   listBox1.Items.Add(item.Value);
}

it loads nothing, what should i do?

3
  • The easiest is probably DataSet.ReadXml, then you can use different tables, like the item table as data source of your ListBox and title as display member. Commented Feb 21, 2022 at 17:51
  • alright i will try that, thanks! Commented Feb 21, 2022 at 18:16
  • @RezaAghaei so i do not seem to understand the documentation... can you give an example on how to use it? i am new to C# and its hard for me to figure out these by myself, thanks in advance Commented Feb 21, 2022 at 18:29

1 Answer 1

1

You are almost there. You can use either of the following solutions:

Using Linq to XML

Use XElement.Load* to load the element, then use .Descendants("item") or .Elements("channel").Elements("item") to get the specific item element:

var items = XElement.Load("http://feeds.bbci.co.uk/news/world/rss.xml")
    .Descendants("item") // OR Use: .Elements("channel").Elements("item")
    .Select(x => new
    {
        title = x.Element("title").Value,
        description = x.Element("description").Value,
        pubDate = x.Element("pubDate").Value,
        link = x.Element("link").Value,
        guid = x.Element("guid").Value,
    }).ToList();

listBox1.DataSource = items;
listBox1.DisplayMember = "title";
textBox1.DataBindings.Add("Text", items, "description");

Using Load a DataSet from XML

Use DataSet.ReadXml to load a data set, then you can use different tables, like the item table as data source of your ListBox and title as DisplayMember.:

var ds = new DataSet();
ds.ReadXml("http://feeds.bbci.co.uk/news/world/rss.xml");
var items = ds.Tables["item"];
listBox1.DataSource = items;
listBox1.DisplayMember = "title";
textBox1.DataBindings.Add("Text", items, "description");
Sign up to request clarification or add additional context in comments.

1 Comment

thanks again, i was trying to figure this out for days!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.