1

Using C# LINQ to XML

I'm trying to omit the first and last nodes in the following XML.

I'm trying to process each node between <node id="2" one="start"> and <node id="4" one="finish">

<root>
  <node id="1">
    <element two="3"/>
    <element two="7"/>
  </node>
  <node id="2" one="start">
    <element two="1"/>
    <element two="2"/>
  </node>
  <node id="3">
    <element two="4"/>
    <element two="4"/>
    <element two="4"/>
    <element two="2"/>
    <element two="6"/>
  </node>
  <node id="4">
    <element two="3"/>
    <element two="7"/>
  </node>
  <node id="5" one="finish">
    <element two="3"/>
    <element two="7"/>
  </node>
  <node id="6">
    <element two="3"/>
    <element two="7"/>
  </node>
<root> 

Is there a to standard approach to this?

4

2 回答 2

1

如果您有一系列XElements 并且您想根据您的条件过滤它们,我认为 LINQ 中没有任何内置的东西可以做到这一点(有SkipWhile()并且TakeWhile()做类似的事情)。

我认为您应该做的是创建一个通用扩展方法,该方法根据第一个和最后一个条件过滤集合,例如:

public static IEnumerable<T> GetBetween<T>(
    this IEnumerable<T> source,
    Func<T, bool> firstPredicate, Func<T, bool> lastPredicate)
{
    bool foundFirst = false;
    foreach (var item in source)
    {
        if (!foundFirst)
            foundFirst = firstPredicate(item);

        if (foundFirst)
        {
            yield return item;

            if (lastPredicate(item))
                break;
        }
    }
}

然后你会像这样使用它:

elements.GetBetween(
    e => (string)e.Attribute("one") == "start",
    e => (string)e.Attribute("one") == "finish")
于 2013-04-24T09:13:59.687 回答
0

我用一些非常简单的逻辑来处理这个问题。

bool processFlag = false;

将这个布尔值从node.element.attribute = "start" 切换到false= "finish" 就可以了!truefalse

于 2013-04-24T06:33:52.813 回答