简体   繁体   中英

C# LINQ XML filtering by attribute

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.

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;

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

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#

:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM