Linq to xml基于子属性选择节点列表

时间:2017-03-08 17:53:43

标签: c# linq

我一直在学习LINQ to XML,但是我遇到了一个有点卡住的情况。

如果我有以下XML:

<root>
    <planes />
    <trains />
    <cars>
        <car name="civic">      
            <property name="4doors" />
            <property name="4tires" />
        </car>
        <car name="f150">
            <property name="2doors" />
            <property name="4tires" />
        </car>
        <car name="crv">
            <property name="4doors" />
            <property name="4tires" />
        </car>      
        <car name="scooter">
            <property name="2tires" />
        </car>      
        <car name="escape">
            <property name="4doors" />
            <property name="4tires" />
        </car>
    </cars>
</root>

如何返回拥有4门的汽车列表?

到目前为止,我已尝试过以下尝试:

// This will return a list of nulls

    var fourDoorCars = xDoc.Descendants("cars").Descendants("car").Descendants("property").Where(x => x.Attribute("name").Value.Contains("4doors")).Select(x => x.Element("car")).ToList();

// This will return a list of all the 4doors properties.

    var fourDoorCars = xDoc.Descendants("cars").Descendants("car").Descendants("property").Where(x => x.Attribute("name").Value.Contains("4doors")).ToList();

1 个答案:

答案 0 :(得分:1)

你可以这样做:

var query=xDoc.Descendants("car")
              .Where(x=> x.Elements("property")
                          .Any(y=>y.Attribute("name").Value.Contains("4doors")));