Showing posts with label Sorting XML using Linq on Attibute. Show all posts
Showing posts with label Sorting XML using Linq on Attibute. Show all posts

Wednesday, April 11, 2012

Sorting XML using Linq on Attribute

//Lets say you want sort an XML on some intiger value something as below.
string mySchedules = "<showschedule>" +
"<fall name=\"FAL\" text=\"Y\" index=\"3\"/>" +
"<spring name=\"SPR\" text=\"Y\" index=\"2\"/>" +
"<winter name=\"WIN\" text=\"Y\" index=\"1\"/>" +
"<summer name=\"SUM\" text=\"Y\" index=\"4\"/>" +
"</showschedule>";

XElement xShows = XElement.Parse(mySchedules);

//This is how you sort
IEnumerable<XElement> sortShows = from s in xShows.Descendants()
orderby (int)s.Attribute("index")
select s;

//This will give you output in the object sortShows as below.

/*
"<showschedule>" +
"<winter name=\"WIN\" text=\"Y\" index=\"1\"/>" +
"<spring name=\"SPR\" text=\"Y\" index=\"2\"/>" +
"<fall name=\"FAL\" text=\"Y\" index=\"3\"/>" +
"<summer name=\"SUM\" text=\"Y\" index=\"4\"/>" +
"</showschedule>";

*/

//You can see the output in the below String
string commaSeperatedSortedMsg = "";
foreach (XElement xE in sortShows)
{
commaSeperatedSortedMsg += " , " + xE.Attribute("index").Value + xE.Attribute("name").Value;

}