Link to home
Start Free TrialLog in
Avatar of Steve Sirica
Steve SiricaFlag for United States of America

asked on

Using Linq to read an XML file with generic list

I have the following XML file structure:
<?xml version="1.0" encoding="utf-8" ?>
<Rates>
  <CarrierRatePlan Name="BMNBIBPNTN450UNWUMM">
    <OBRatePlan>WLPL1</OBRatePlan>
    <RateNetCode>BAMBL</RateNetCode>
    <Feats>
      <Feat>
        <Code>WIRELE</Code>
        <NetCode>NONET</NetCode>
      </Feat>
      <Feat>
        <Code>WLVMS1</Code>
        <NetCode>NONET</NetCode>      
    </Feat>
    </Feats>
  </CarrierRatePlan>    
</Rates>

Open in new window


I have the following classes:
Public Class clsRate
    Public Property CarrierRatePlan As String
    Public Property OBRatePlan As String
    Public Property RateNetCode As String
    Public Property Feats As List(Of clsFeat)
End Class


Public Class clsFeat
    Public Property Code As String
    Public Property NetCode As String
End Class

Open in new window


I thought I could get a record using the following function:
    Public Function GetRate(aRate As String) As clsRate
        Dim xml As XDocument
        Try
            xml = XDocument.Load(Server.MapPath("~/RateRefFile.xml"))

            Return (From c In xml.Descendants("CarrierRatePlan")
                    Where c.Attribute("Name").Value.Equals(aRate.Trim)
                    Select New clsRate() With
                        {
                        .CarrierRatePlan = c.Attribute("Name").Value,
                        .OBRatePlan = c.Element("OBRatePlan").Value,
                        .RateNetCode = c.Element("RateNetCode").Value,
                        .Feats = (From f In c.Descendants("Feats")
                                  Select New clsFeat() With
                                          {
                                          .Code = f.Element("Code").Value,
                                          .NetCode = f.Element("NetCode").Value
                                          })
                        }
                   ).FirstOrDefault()

        Catch ex As Exception
            Throw
        End Try
    End Function

Open in new window


I get the following error:

"Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,clsFeat]' to type 'System.Collections.Generic.List`1[clsFeat]'."

So what am I doing wrong?
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Steve Sirica

ASKER

Outstanding!  Thank you Fernando.  I knew I was close.  Thanks for getting me the rest of the way.
Not a Problem SSirica, glad I was able to help.