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;

}

3 comments:

  1. Can you help me? I tried your example and can't quite get it to work.

    I am first iterating thru some data and building an XElement in each loop. Within each loop, I add the XElement data to an ArrayList as such:

    foreach(var e in eachElement)
    {
    XElement expectedXml = new XElement("RECORD",
    new XAttribute("DOMAIN_NAME", e.Attribute("name").Value),
    new XAttribute("DOMAIN_ID", e.Attribute("domainid").Value));

    returnList.Add(expectedXml);
    }


    When I am done looping, I have all my xml strings in an ArrayList, so I put it into an IEnumerable as shown:

    IEnumerable eachExpElement = returnList.OfType();

    Now, I need to sort this by the DOMAIN_NAME attribute and return it to an ArrayList.

    I tried this:
    eachExpElement.OrderByDescending(a => a.Attribute("DOMAIN_NAME").Value).ToList();

    foreach (var x in eachExpElement)
    {
    returnList2.Add(x).ToString();
    }

    and while it runs - it doesn't seem to sort by that attribute.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I can't get this to show in post - but my returnList.OfType is XElement

    ReplyDelete