【问题标题】:How to extract a certain sub-elements depend on the condition using Linq to XML如何提取某些子元素取决于使用Linq to XML的条件
【发布时间】:2012-01-02 20:41:52
【问题描述】:

我有 XML(不完全是这么简单,但对于我的问题来说已经足够了)。

如果我编写如下代码

    var xdoc = XDocument.Parse(@"
<Root>
    <Item>
        <Node1>Value 1</Node1>
        <Node2>Value 2</Node2>
        <Node3>Value 3</Node3>
        <Node4>Value 4</Node4>
        <Node5>Value 5</Node5>
        <Node6>Value 6</Node6>
    </Item>  
</Root>");

var results = xdoc.Root
    .Elements("Item")
    .Descendants()
    .Select(e => new { ElementName = e.Name, ElementValue = e.Value });

这将为我提供“Item”元素的所有后代(节点名称和节点值)的结果列表。我想问的是如何根据条件获得不同的数据集。例如,如果 Node1 或 Node2 有一个值(非空),那么我只想要 Node1 和 Node2 的结果列表(节点名称和值),否则结果列表应该显示其他节点,即 Node3、Node4、Node5 和Node6(节点名称和值)。请帮忙。谢谢。

【问题讨论】:

    标签: linq-to-xml


    【解决方案1】:

    我不确定我是否完全理解您的问题。但是,如果我做对了,那么您只需要添加这样的条件:

    if (condition)
        results = results.Take(2);
    else
        results = results.Skip(2);
    

    因此,如果 condition 为真,那么您的结果序列中将只有前 2 个节点。如果condition 为假,那么您将只有剩余的元素。

    我对您的问题的第一个解释是,您需要在查询中添加对 Where 的调用,这样您就只有在结果集中实际包含值的元素。看起来像这样:

    var results = xdoc.Root
        .Elements("Item")
        .Descendants()
        .Where(e => !string.IsNullOrEmpty(e.Value))
        .Select(e => new { ElementName = e.Name, ElementValue = e.Value }); 
    

    【讨论】:

      【解决方案2】:

      你的条件有点……奇怪。

      var query =
          from item in doc.Root.Elements("Item")
          let elements = item.Elements()
          let firstTwo = elements.Take(2)
          let descendants = firstTwo.All(e => !String.IsNullOrWhiteSpace(e.Value))
            ? firstTwo.DescendantsAndSelf()
            : elements.Skip(2).DescendantsAndSelf()
          from e in descendants
          select new
          {
              ElementName = e.Name,
              ElementValue = e.Value,
          };
      

      【讨论】:

        猜你喜欢
        • 2010-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-10
        • 1970-01-01
        相关资源
        最近更新 更多