【问题标题】:LINQ to XML - Selecting elements based on values that exist in other elementsLINQ to XML - 根据其他元素中存在的值选择元素
【发布时间】:2010-10-16 14:49:29
【问题描述】:

我想我正在突破 LINQ to XML 的能力范围,但我想选择一组元素,这些元素包含的值与另一个元素节点中包含的值相匹配。

在下面的 XML 中,我只想选择包含特定产品 ID 的 AvailableOptions 元素中的值的“Option”元素。

类似于下面的伪代码:

选择选项名称所在的所有选项(Select AvailableOptions Where ProductID = "xxx")

<Agents>
<Agent ID="1">
    <Login>111</Login>
    <Password>pass</Password>
    <Products>
        <Product ID="xxx">
            <AvaiableOptions>aaa,bbb</AvaiableOptions>
        </Product>
    </Products>
    <Products>
        <Product ID="yyy">
            <AvaiableOptions>bbb,ccc</AvaiableOptions>
        </Product>
    </Products>
    <Products>
        <Product ID="zzz">
            <AvaiableOptions>aaa,ccc</AvaiableOptions>
        </Product>
    </Products>
    <Options>
        <Option>
            <Name>aaa</Name>
            <Value>10</Value>
        </Option>
        <Option>
            <Name>bbb</Name>
            <Value>20</Value>
        </Option>
        <Option>
            <Name>ccc</Name>
            <Value>30</Value>
        </Option>
    </Options>
</Agent>

【问题讨论】:

    标签: linq linq-to-xml


    【解决方案1】:

    这是我的尝试,虽然有点冗长。希望对您有所帮助。

    var query = from agent in agents.Descendants("Agent")
                from products in agent.Descendants("Products")
                from product in products.Descendants("Product")
                where product.Attribute("ID").Value == "xxx"
                from options in agent.Descendants("Options")
                from option in options.Descendants("Option")
                where product.Element("AvaiableOptions").Value.Contains(option.Element("Name").Value)
                select option;
    

    【讨论】:

    • 是的,就是这样。谢谢。我只是想不通如何构建这样的查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    相关资源
    最近更新 更多