0

I have the following XML:

<PlayerSetup>
    <CardDeck name="deckOfCards"/>
    <Card name="one"/>
    <Card name="two"/>
    <Card name="three"/>
    <Card name="four"/>
    <Token name="four"/>
</PlayerSetup>

I need to retrieve only the elements which attributes name="four", I have the following code:

var query = from d in xdoc.Descendants("PlayerSetup")
             where (string)d.Attribute("name").Value == "four"
             select d;

Which of course, is not working, returns no elements. Any idea ? Thanks.

3
  • You mean you want 1) the PlayerSetup elements with a descendant element with attribute name="four"; or 2) the descendant elements of PlayerSetup with attribute name="four"? Commented Sep 30, 2015 at 20:22
  • name is an attribute of Card not PlayerSetup Commented Sep 30, 2015 at 20:24
  • Yes, name is attribute of Card, not PlayerSetup, @Eser thanks for your answer, I was actually close to it but I didn't know that I could use multiple Descendants() to keep "digging" into the xml tree. Commented Sep 30, 2015 at 21:53

3 Answers 3

2

If you want the descendant elements under the "PlayerSetup" elements with name="four", you can do:

        var query = from d in xdoc.Descendants("PlayerSetup").Descendants()
                    where (string)d.Attribute("name") == "four"
                    select d;

If you want the "PlayerSetup" elements who have at least one descendant element with name="four", you can do:

        var query = from d in xdoc.Descendants("PlayerSetup")
                    where d.Descendants().Any(c => (string)c.Attribute("name") == "four")
                    select d;
Sign up to request clarification or add additional context in comments.

Comments

1

You are wanting to look at the Descendants of PlayerSetup, so grab those:

var query = from d in xdoc.Descendants("PlayerSetup").Descendants()
            where d.Attribute("name")?.Value == "four"
            select d;

//query.Count == 2

this solution uses C#6 syntax

Comments

-1

I think your problem is already known for a long time.

You can find it here: LINQ to XML query attributes

or here: How to get attribute names of element in xml by LINQ in C#

:)

1 Comment

I already saw the first link and didn't work for my example, but thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.