I am trying to parse the following xml file : http://reports.ieso.ca/public/DispUnconsHOEP/PUB_DispUnconsHOEP_20110714.xml
My goal is to get the maximum price with its associated hour and the minimum price with its associated hour.
The logic that I am applying is as follows:
Parse the Xml file and pass it to a IList which contains pairs of hour and price
Sort the IList in Descending order based on 开发者_StackOverflow中文版the price
Retrieve the first value in the IList as the maximum value whereas the last value in the IList as the minimum value.
My Code is:
XNamespace nsPriceHr = "http://www.theIMO.com/schema";
XDocument xDocument =
XDocument.Load("http://reports.ieso.ca/public/DispUnconsHOEP/PUB_DispUnconsHOEP_20110714.xml");
XElement xEl1 = xDocument.Element(nsPriceHr + "IMODocument");
XElement xEl2 = xEl1.Element(nsPriceHr + "IMODocBody");
XElement xEl3 = xEl2.Element(nsPriceHr + "HOEPs");
var data = (from x in xEl3.Descendants(nsPriceHr + "HOEP")
orderby x.Element(nsPriceHr + "Price").Value descending
select new HourPrice
{
Hour = x.Element(nsPriceHr + "Hour").Value,
Price = x.Element(nsPriceHr + "Price").Value
})
.ToList();
My Problem is: the List is not getting sorted as expected. The HourPrice object which takes the two values of Hour and Price has both data members as string.
I am using C#, .NET 3.5 SP1 and working on winforms. Any help appreciated
Try using System.Convert. In particular, you may be interested in ToInt32 and ToDecimal. These functions take a string (or one of various other data types), and convert it to an int or a decimal respectively.
var data = (from x in xEl3.Descendants(nsPriceHr + "HOEP")
orderby System.Convert.ToDecimal(x.Element(nsPriceHr + "Price").Value) descending
select new HourPrice
{
Hour = System.Convert.ToInt32(x.Element(nsPriceHr + "Hour").Value),
Price = System.Convert.ToDecimal(x.Element(nsPriceHr + "Price").Value)
})
.ToList();
Edit:
Here is one way you might check for missing values:
string valueString = x.Element("ElementName").Value;
int value = String.IsNullOrEmpty(valueString) ? 0 : Convert.ToInt32(valueString);
If your problem is that the strings aren't empty, but aren't in the right format either, you will have to convert them to the right format before you convert. I.e., you must strip the $ from a string like $6.47.
加载中,请稍侯......
精彩评论