Note that there are some explanatory texts on larger screens.

plurals
  1. POSorting XML nodes based on DateTime attribute C#, XPath
    text
    copied!<p>I have a XML Structure that looks like this.</p> <pre><code>&lt;sales&gt; &lt;item name="Games" sku="MIC28306200" iCat="28" sTime="11/26/2008 8:41:12 AM" price="1.00" desc="Item Name" /&gt; &lt;item name="Games" sku="MIC28307100" iCat="28" sTime="11/26/2008 8:42:12 AM" price="1.00" desc="Item Name" /&gt; ... &lt;/sales&gt; </code></pre> <p>I am trying to find a way to SORT the nodes based on the sTime attribute which is a DateTime.ToString() value. The trick is I need to keep the Nodes in tact and for some reason I can't find a way to do that. I'm fairly certain that LINQ and XPath have a way to do it, but I'm stuck because I can't seem to sort based on DateTime.ToString() value.</p> <pre><code>XPathDocument saleResults = new XPathDocument(@"temp/salesData.xml"); XPathNavigator navigator = saleResults.CreateNavigator(); XPathExpression selectExpression = navigator.Compile("sales/item/@sTime"); selectExpression.AddSort("@sTime", XmlSortOrder.Descending, XmlCaseOrder.None, "", XmlDataType.Number); XPathNodeIterator nodeIterator = navigator.Select(selectExpression); while( nodeIterator.MoveNext() ) { string checkMe = nodeIterator.Current.Value; } </code></pre> <p>I also need to maintain a pointer to the NODE to retrieve the values of the other attributes. </p> <p>Perhaps this isn't a simple as I thought it would be.</p> <p>Thanks.</p> <p><strong>Solution</strong>: Here's what I ended up using. Taking the selected answer and the IComparable class this is how I get the XML nodes sorted based on the sTime attribute and then get the all the attributes into the appropriate Arrays to be used later.</p> <pre><code> XPathDocument saleResults = new XPathDocument(@"temp/salesData.xml"); XPathNavigator navigator = saleResults.CreateNavigator(); XPathExpression selectExpression = navigator.Compile("sales/item"); XPathExpression sortExpr = navigator.Compile("@sTime"); selectExpression.AddSort(sortExpr, new DateTimeComparer()); XPathNodeIterator nodeIterator = navigator.Select(selectExpression); int i = 0; while (nodeIterator.MoveNext()) { if (nodeIterator.Current.MoveToFirstAttribute()) { _iNameList.SetValue(nodeIterator.Current.Value, i); } if (nodeIterator.Current.MoveToNextAttribute()) { _iSkuList.SetValue(nodeIterator.Current.Value, i); } ... nodeIterator.Current.MoveToParent(); i++; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload