开发者

How do I select XML elements into a strongly-typed collection using LINQ?

I am trying to wrap my brain around using LINQ as a means of working with XML d开发者_StackOverflow中文版ata and I'm having a problem figuring out the best way to select elements into a strongly-typed collection. I'm sure there's some minute detail I'm missing, but I can't seem to see it.

Here is a sample of my XML File:

    <users>
      <User>
        <UserId>a3ba555e-9dbe-4f5e-a8b0-56be91a99eae</UserId>
        <Password>FCC2427123934BC2A06297847574A50E</Password>
        <Username>TestTEst</Username>
        <FirstName>Test</FirstName>
        <LastName>TestTEst</LastName>
      </User>
      <User>
        <UserId>500629d5-c22a-4585-bc85-330391f44fac</UserId>
        <Password>FCC2427123934BC2A06297847574A50E</Password>
        <Username>TestTEst</Username>
        <FirstName>Test</FirstName>
        <LastName>TestTEst</LastName>
      </User>
      <User>
        <UserId>bd6b78db-9cd7-403b-a757-a8c013bdc523</UserId>
        <Password>FCC2427123934BC2A06297847574A50E</Password>
        <Username>TestTEst</Username>
        <FirstName>Test</FirstName>
        <LastName>TestTEst</LastName>
      </User>
</users>

When I create an object using the following code:

Dim userList = From u In users.Descendants("user") _
               Select u

Then userList will contain the elements of my XML file. If I try to select the XML file into a strongly-typed collection instead:

Dim userList = (From u In users.Descendants("user") _
               Select New User With { _
                   .UserId = New Guid(u.Attribute("UserId").Value), _
                   .Username = u.Attribute("Username").Value, _
                   .Password = u.Attribute("Password").Value, _
                   .FirstName = u.Attribute("FirstName").Value, _
                   .LastName = u.Attribute("LastName").Value _
               }).ToList()

Then userList is empty. This is the same whether or not I explicitly specify the type of userList (List(Of User)). What am I doing wrong? What is the correct way to create a strongly-typed collection directly from XML?

Thanks,

Mike


I think your problem here is that "UserID", "Username", "Password", etc. are not attributes of the User tag, they are sub-elements. Might want to try this:

Dim userList = (From u In users.Descendants("user") _
               Select New User With { _
                   .UserId = New Guid(u.Decendants("UserId").First().Value), _
                   .Username = u.Decendants("Username").First().Value, _
                   .Password = u.Decendants("Password").First().Value, _
                   .FirstName = u.Decendants("FirstName").First().Value, _
                   .LastName = u.Decendants("LastName").First().Value _
               }).ToList()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜