Brian
Brian

Reputation: 558

Sorting XML With LINQ

I have the following XML:

<TRUCK Counter="0">
  <CARRIER>A PLUS EXPEDITING &amp; LOGISTICS INC.</CARRIER>
  <CARRIERPHONE>(000)000-0220</CARRIERPHONE>
  <UNITNO>100673V</UNITNO>
  <UNITTYPE>CARGO VAN                     </UNITTYPE>
  <DISTANCE>13</DISTANCE>
  <AVAILABLE>06/14/2012 09:00</AVAILABLE>
  <STATUS>In Service</STATUS>
  <LOCATION>REDFORD, MI</LOCATION>
  <NOTE> check 1st</NOTE>
  <PAYLOAD>3000</PAYLOAD>
  <DIMS>
    <BOXLENGTH>108</BOXLENGTH>
    <BOXWIDTH>53</BOXWIDTH>
    <BOXHEIGHT>48</BOXHEIGHT>
  </DIMS>
  <DOMICILE>US</DOMICILE>
  <SATELLITE>N</SATELLITE>
</TRUCK>

I'm selecting the elements I want and sorting them in a method that gets passed the column to sort on:

public static XDocument GetSortedTrucksXml(string xmlBuffer, string sortColumn)
{
    XDocument xdoc = XDocument.Parse(xmlBuffer);

    int Counter = 0;

    var trucks = from s in xdoc.Element( "TRUCKS" ).Elements( "TRUCK" )
                 orderby ( string )s.Element( sortColumn )
                 select new XElement( "TRUCK",
                        s.Element( "CARRIER" ),
                        s.Element( "CARRIERPHONE" ),
                        s.Element( "UNITNO" ),
                        s.Element( "UNITTYPE" ),
                        s.Element( "DISTANCE" ),
                        s.Element( "AVAILABLE" ),
                        s.Element( "STATUS" ),
                        s.Element( "LOCATION" ),
                        s.Element( "NOTE" ),
                        s.Element( "PAYLOAD" ),
                        s.Element( "DIMS" ),
                        s.Element( "DOMICILE" ),
                        s.Element( "SATELLITE" ) );

    XDocument newDoc = new XDocument( new XElement( "TRUCKS" ) );

Note that I'm getting the children of by just specifying the parent element.

My question is how would I sort on BOXLENGTH, BOXWIDTH or BOXHEIGHT? If I send in "DIMS/BOXLENGTH" as the sort column, I get an error.

Upvotes: 1

Views: 146

Answers (1)

Botz3000
Botz3000

Reputation: 39600

You can use the XPath Extension methods:

// You need this namespace
using System.Xml.XPath;

// use this in your query
orderby (string)s.XPathSelectElement(sortColumn)

Upvotes: 1

Related Questions