views:

1581

answers:

4

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.

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...

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.

+1  A: 

You can use LINQ to XML - http://msdn.microsoft.com/en-us/library/bb387098.aspx.

Ivan Zlatanov
+1  A: 

No problem - see System.Data.DataSet.ReadXml() which will load your XML data into a DataSet.

A quick check:

DataSet mySet = new DataSet();
mySet.LoadXml("myfile.xml");
myTable = mySet.Tables[0];
myCols = myTable.Columns;
Console.Writeline("Column Names: {0}, {1}, {2}",
    myCols[0].ColumnName, myCols[1].ColumnName, myCols[2].ColumnName);

... result ...
Column Names: Name, Artist, Genre

You should assign myTable to the .DataSource property of some control.

gimel
+2  A: 

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();

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.

Andreas Grech
A: 

ObjectListView has a DataListView which is a data-bindable version of a .NET ListView (WinForms). ObjectListView also automatically handles categorizing into groups, by Artist or Genre, or whatever other information is showing the list.

The open-source program, LyricsFetcher, reads the entire iTunes library from XML and uses an ObjectListView to display the songs. Loading 10,000+ and showing them in this fashion takes less than one second on my mid-range laptop.

Grammarian