簡體   English   中英

Linq to xml基於子屬性選擇節點列表

[英]Linq to xml select list of nodes based on child attribute

我一直在學習LINQ to XML,但是遇到了一個有點卡住的senario。

如果我有以下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();

你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM