开发者

My LINQ Query is Returning only 1 result

开发者 https://www.devze.com 2023-02-12 07:24 出处:网络
My LINQ Query is only returning the first result (Class). Here is the code that I am using: XDocument xmlDoc = XDocument.Load(\"Decks/Test.xml\");

My LINQ Query is only returning the first result (Class). Here is the code that I am using:

        XDocument xmlDoc = XDocument.Load("Decks/Test.xml");
        List<Cards> tempdeck = (from deck in xmlDoc.Elements("Deck")
                开发者_如何学运维                select new Cards
                                 {
                                     Name = deck.Element("Type").Value

                                 }).ToList<Cards>();

        foreach (var item in tempdeck)
        {
            ((MessageBroker)App.Current.Resources["MessageBroker"]).GameLog.Add(item.Name.ToString());

        }

This is what my XML file looks like:

<Deck>
  <Type>
    <Name>Class</Name>
  </Type>
  <Type>
    <Name>stsfs</Name>
  </Type>
  <Type>
    <Name>Class</Name>
  </Type>
  <Type>
      <Name>Class</Name>
    </Type>
</Deck>

I am formatting it this way because when I get it to work I want to add multiple properties to the query - not just name.

Thanks in advance!


It isn't clear from your sample, but it appears you have one Deck element with multiple Type child elements. Your code is assuming the opposite, i.e. multiple decks, each with one (or one interesting) type-child.

Try this instead:

( from type in xmlDoc.Element("Deck").Elements("Type")
  select new Cards { Name = type.Value }
).ToList()

A "cards" is produced from each type-child of the only deck.

If you do have multiple decks, go with Mark Cidade's answer.


In your query, you only select from the single Deck element and then choose the first Type element. You need to select from each Type element:

    List<Cards> tempdeck = (from deck in xmlDoc.Elements("Deck")
                            from type in deck.Elements("Type")
                            select new Cards
                             {
                                 Name = type.Value

                             }).ToList<Cards>();
0

精彩评论

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

关注公众号