简体   繁体   English

C#LINQ XML按属性过滤

[英]C# LINQ XML filtering by attribute

I have the following XML: 我有以下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: 我只需要检索属性名称为“ four”的元素,我有以下代码:

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: 如果您希望"PlayerSetup"元素下的后代元素的名称为“ four”,则可以执行以下操作:

        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: 如果希望"PlayerSetup"元素至少具有一个名称为“ four”的后代元素,则可以执行以下操作:

        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: 你是想看看Descendants PlayerSetup ,因此,抓住那些:

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 此解决方案使用C#6语法

I think your problem is already known for a long time. 我认为您的问题已经很长时间了。

You can find it here: LINQ to XML query attributes 您可以在这里找到它: LINQ to XML查询属性

or here: How to get attribute names of element in xml by LINQ in C# 或者在这里: 如何在C#中通过LINQ获取xml中的元素的属性名称

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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