I have a xml and I want to sort it by date.my code till now is this
XmlDocument doc = new XmlDocument();
doc.Load("/ABC.xml");
XPathNavigator nav = doc.CreateNavigator();
//doing some filtering and creating xpath expression based on that
XPathExpression expression = nav.Compile(xpath);
XPathExpression sortexpression = nav.Compile("/categories/category/date/text()");
DateComparer dc = new DateComparer();
//expression.AddSort("sortexpression", dc);
Edited: I have changed this to
expression.AddSort(sortexpression,dc);
now there is no error but sortin is not working properly and when I while I came to know that in datecomparer class only first date of my xml is going and because of that there is no sorting going on. But why only my first date of xml is going into datecomparer.Any Idea where I am wrong??
XPathNodeIterator iterator = nav.Select(expression);
later on binding this iterator with my repeater
public class DateComparer : IComparer
{
public DateComparer() { }
public int Compare(object date1, object date2)
{
DateTime d1 = Convert.ToDateTime(date1);
DateTime d2 = Convert.ToDateTime(date2);
return d1.CompareTo(d2);
}
}
My xml is like this
<categories>
<category>
<title>ABCD<title>
<date>2002-01-01<date>
<category>
<categories>
Date i m givin is in yyyy-mm-dd format. I have tried date in others format like mm/dd/yyyy and dd/mm/yyyy also.
//but when i m executing this code I m getting the error ” string was not recognized as a valid Datetime”.Any idea what is the problem in my code?
Edited:No error see above
Assuming that the dates are read as strings you’re going to need to provide an
IFormatProviderto yourConvert.ToDateTimemethod as the date you are using is non-standard. If you don’t then the conversion method will use the current culture.UK English would be day-month-year and US English would be month-day-year for example.
For year-month-day you may even need a custom format provider, or you could use
DateTime.ParseExact: