1

我有以下 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>

我正在选择我想要的元素并以一种方法对它们进行排序,该方法通过列进行排序:

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

请注意,我只是通过指定父元素来获取子元素。

我的问题是如何对 BOXLENGTH、BOXWIDTH 或 BOXHEIGHT 进行排序?如果我将“DIMS/BOXLENGTH”作为排序列发送,则会出现错误。

4

1 回答 1

1

您可以使用XPath 扩展方法

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

// use this in your query
orderby (string)s.XPathSelectElement(sortColumn)
于 2012-06-14T14:05:16.343 回答