[英]How do I parse an XML file into a ListBox
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:我正在尝试将此 883812976388 文件http://feeds.bbci.co.uk/news/world/rss.xml解析为可视化 C# 中的列表框,我尝试了很多不同的方法,但没有一个有效,这就是一个那种作品:
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唯一的问题是,它加载了错误的 object如果我将它设置为
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?它没有加载任何内容,我该怎么办?
You are almost there.你快到了。 You can use either of the following solutions:您可以使用以下任一解决方案:
Using Linq to XML使用Linq 到 XML
Use XElement.Load * to load the element, then use .Descendants("item") or .Elements("channel").Elements("item") to get the specific item element:使用XElement.Load * 加载元素,然后使用.Descendants("item")或.Elements("channel").Elements("item")获取具体的项目元素:
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使用从 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.:使用DataSet.ReadXml加载数据集,然后您可以使用不同的表,例如项目表作为 ListBox 的数据源,标题作为 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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.