【问题标题】:LINQ XML obtaining child nodes of parent nodeLINQ XML获取父节点的子节点
【发布时间】:2011-12-05 02:10:49
【问题描述】:

请在下面找到 xml 数据。我想使用 LINQ 查询获取键为“Sub1”和“Sub2”的节点,因为我知道父节点具有 url="#"、title="item 1" 和 key="Item1"。

<root>
<node title="Partner" url="" description="99" roles="GuidIdHere"></node>
<node title="Test" url="" description="51" roles="8b0c0c4f" key="sample">
    <node url="#" title="item 1" description="" key="Item1">
        <node url="#" title="Sub 1" description="" key="Sub1" />
        <node url="#" title="Sub 2" description="" key="Sub2" />
    </node>
    <node url="#" title="item 2" description="" key="Item2" />
    <node url="#" title="item 3" description="" key="Item3" />
</node>
</root>

谢谢!

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:
    var result = from x in doc.Root.Descendents("node")
                 where (string)x.Attribute("url") == "#"
                    && (string)x.Attribute("title") == "item 1"
                    && (string)x.Attribute("key") == "Item1"
                 from y in x.Elements("node")
                 where (string)x.Attribute("key") == "Sub1"
                    || (string)x.Attribute("key") == "Sub2"
                 select y;
    

    【讨论】:

    • 我只需将 doc.Root.Descendants 更改为 doc.Descendants,否则这是完美的!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多