tags:

views:

365

answers:

3

I have an xml document that I am creating using the loop below and the XML writer from C#. It currently works fine, but I wanted to implement a solution where every time the XML is written it automatically sorts it ascending using the driveStart field. I know people say you should do this in XSLT but I am having a hard time finding a good example to follow. Anyone have any experience in this that I can use? Any help is greatly appreciative.

XmlDocument doc = new XmlDocument();
XmlElement rn = doc.CreateElement("DriveLayout");
XmlElement dn = null;
XmlAttribute xa, xa1, xa2, xa3, xa4, xa5, xa6;
doc.AppendChild(rn);

foreach (GridItem item in this.fileSystemGrid.Items)
{
  dn = doc.CreateElement("Drive");
  xa = doc.CreateAttribute("driveTime");
  xa.Value = item["DriveTime"].ToString();
  xa1 = doc.CreateAttribute("driveStart");
  xa1.Value = item["DriveStart"].ToString();
  xa2 = doc.CreateAttribute("driveEnd");
  xa2.Value = item["DriveEnd"].ToString();
}

dn.SetAttributeNode(xa);
dn.SetAttributeNode(xa1);
dn.SetAttributeNode(xa2);
rn.AppendChild(dn);

return doc.InnerXml;
A: 

Why do you want to sort it? How will it be used? Normally, XML is just data, and isn't sorted just to make it look pretty.

John Saunders
The xml is later parsed out for use by another program. The problem is that with this particular program runs it must go in order from smallest to largest. Thus I want to sort the XML right before it is written so that the other program can do its job correctly
Splashlin
Then this is really the job of the other program. Otherwise, if it changes its requirements (maybe to sort on DriveEnd in addition to DriveStart) then your code will have to change. Your code shouldn't really have knowledge of how the other program wants data sorted.
John Saunders
+3  A: 

Sort your collection by their DriveStart before using the xml writer.

Francis B.
sorry I'm new to C#. So something along the lines of item.Sort = ???
Splashlin
Chances are you should talk to the more senior developers on your team about this. Among other things, it's a little strange for you to be taking data out of the grid itself instead of taking the data from what the grid is bound to. Next question will be what version of Visual Studio you're using.
John Saunders
i can't seem to find how to sort a grid collection. I see how to do a gridview and others but not a whole gridcollection
Splashlin
I'm using visual studio 2008
Splashlin
@Splashlin As John Saunders said, manipulating GridItem is not the best way to achieve that. It is complicated to give you an perfect example because some information are missing but if you populated your grid with, per example, a collection of drive item you could sort you collection with LINQ.
Francis B.
+1  A: 
Tomalak