tags:

views:

62

answers:

2

I've an Xml file like

<SampleFile>
 <Data>
   <Element Val="8" /> 
   <Element Val="10" /> 
   <Element Val="12" /> 
   <Element Val="14" /> 
   <Element Val="16" /> 
   <Element Val="9" /> 
   <Element Val="11" /> 
   <Element Val="13" /> 
   <Element Val="15" /> 
   <Element Val="17" /> 
 </Data>
</SampleFile>

i need to read the attribute value of" Val" and convert it to Int32 , then sort and then add to the list

now i'm using like:

  List<Int32> lst = (XDocument.Load("\\Sample.xml").Descendants("Element").Select(l_Temp => l_Temp.Attribute("Val").Value.ToString()).Cast<Int32>().OrderBy(nTemp => nTemp)).ToList();

but its not working properly

please give me a better solution

+2  A: 

First let's reformat the code a bit so we can actually see what's going on:

List<Int32> lst = XDocument.Load("\\Sample.xml")
                     .Descendants("Element")
                     .Select(l_Temp => l_Temp.Attribute("Val").Value.ToString())
                     .Cast<Int32>()
                     .OrderBy(nTemp => nTemp)
                     .ToList();

Now, your Select clause is selecting a sequence of strings - although the ToString call is unnecessary as XAttribute.Value is already a string.

You're then trying to use Cast<Int32> to convert those strings into integers. That's not what Cast<T>() does. It only performs reference an unboxing conversions. Fortunately, XAttribute has an explicit conversion to int which makes all of this much simpler:

List<Int32> lst = XDocument.Load("\\Sample.xml")
                           .Descendants("Element")
                           .Select(l_Temp => (Int32) l_Temp.Attribute("Val"))
                           .OrderBy(nTemp => nTemp)
                           .ToList();
Jon Skeet
Hi Jon. What do you mean with "It only performs reference an unboxing conversions"
chiccodoro
+1 @ Jon Skeet Thank you
Pramodh
A: 

http://msdn.microsoft.com/en-us/library/ms459356.aspx

I think, this will help u..

There's absolutely no need to use a schema file here.
Jon Skeet