Visual C#2008,读取XML文件并填充listView [英] Visual C# 2008, reading an XML file and populating a listView

查看:266
本文介绍了Visual C#2008,读取XML文件并填充listView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的最终目标...拿这个xml文件..

Here is my ultimate goal... to take this xml file..

<?xml version="1.0"?>
<Songs>
   <Song>
      <Name>Star Spangled Banner</Name>
      <Artist>Francis Scott Key</Artist>
      <Genre>Patriotic</Genre>      
   </Song>
   <Song>
      <Name>Blankity Blank Blank</Name>
      <Artist>Something Something</Artist>
      <Genre>Here here</Genre>
   </Song>
</Songs>

并在应用程序启动时将其加载到列表视图组件中。我也想让歌曲被艺术家或流派分为类别。

and load it into a list view component when my application starts up. I also want to have the "Songs" be separated into categories by either Artist or Genre.

我是Visual C#的新手,但我一直在编码一个而我真的只是在寻找一个人来指向我正确的方向...

I'm new to Visual C#, but I've been coding for a while, so I'm really just looking for someone to point me in the right direction here...

在谷歌看来,人们似乎读取XML文件,循环内容以填充列表视图组件。对于所有这些数据集和绑定源可用的数据来说,这似乎是不切实际的。看起来应该有一种方式,我将XML文件加载到数据集中,然后将绑定源链接到数据集,然后将列表视图链接到绑定源(或沿着这些行)。尽管我可以在这些组件中,似乎找不到任何setter方法,这样做,我也查看了这些组件的属性窗口,没有成功。

Looking on google it looks like people seem to read XML files and loop through the contents to populate a list view component. Which seems impractical on the count that there are all of these "dataset" and "binding source" things available. It looks like there should be a way that I load the XML file into a data set, then link a binding source to the dataset, and then finally link the listview to the binding source (or something along these lines).. Though I can't seem to find any "setter" methods on any of these components which would do this, I've also looked up and down the "properties" window for these components with no success.

推荐答案

使用 Linq to XML ,您可以执行以下操作:

With Linq to XML, you can do something like the following:

XDocument loaded = XDocument.Load("myfile.xml");

var songs = from x in loaded.Descendants( "Song" )
select new
{
    Name = x.Descendants( "name" ).First().Value,
    Category = x.Descendants( "artist" ).First().Value,
    Genre = x.Descendants( "genre" ).First().Value,
}; //Returns an anonymous custom type

MyListView.DataSource = songs;  MyListView.DataBind();

现在您可以使用<$ c中的三个字段(刚刚返回的匿名类型) $ c> ListView 的模板,您的数据将会显示。

Now you can use the three fields (from the anonymous type you just returned) in your ListView's template and your data will be displayed.

这篇关于Visual C#2008,读取XML文件并填充listView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆