【问题标题】:linq to xml Select only nodes that have certain elementslinq to xml 仅选择具有某些元素的节点
【发布时间】:2012-03-06 10:44:17
【问题描述】:

使用以下 xml,我只想返回 <category domain="Portal Sub" value="Events"> 节点中有子元素的项目。

我尝试使用以下代码,但它仍然返回所有节点。 任何帮助将不胜感激,因为我似乎无法弄清楚如何仅获取存在子节点的项目。

  <item guid="123">
  <title>test1</title>
        <category domain="Target">Business Decision Makers</category>
        <category domain="Target">Individual Customers</category>
        <category domain="Target">IT Decision Makers</category>
        <category domain="Portal" value="IT Network">
            <category domain="Portal Sub" value="Events">
                <category domain="Portal Sub" value="Forum" />
            </category>
        </category>
    </item>
    <item guid="456">
    <title>test2</title>
        <category domain="Target">IT managers</category>
        <category domain="Target">IT Professional</category>
        <category domain="Portal" value="IT Network">
            <category domain="Portal Sub" value="Events" />
        </category>
    </item>





var getFilteredItems = (from item in xdoc.Descendants("item")
                            where item.Descendants("category").Descendants("category").Any()
                            select new
                             {
                                     etype = (from x in item.Elements("category").Elements("category")
                                          where x.Attribute("value").Value == "Events"
                                          select new
                                          {
                                              cctype = x.Descendants("category").Select(i => i.Attribute("value").Value ?? "")
                                          }).First()

                             }).ToList();

【问题讨论】:

    标签: c# linq-to-xml


    【解决方案1】:
    from item in xdoc.Descendants("item")
    where item.Descendants("category").Any(c => (string)c.Attribute("domain") == "Portal"
      && (string)c.Attribute("value") == "Events" && c.Elements().Any())
    select ...
    

    【讨论】:

    • 感谢马丁,工作完美。我玩弄了属性值,但错过了 Elements.Any 部分。感谢您的快速帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多