基于Attribute省略XML中的节点

时间:2013-04-24 05:48:11

标签: c# xml linq-to-xml

使用C# LINQ to XML

我正在尝试省略以下XML中的第一个和最后一个节点。

我正在尝试处理<node id="2" one="start"><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> 

对此有标准方法吗?

2 个答案:

答案 0 :(得分:1)

如果你有XElement的序列并且你想根据你的条件过滤它们,我认为LINQ中没有内置任何内容可以做到这一点(有{{1}和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;
        }
    }
}

答案 1 :(得分:0)

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

bool processFlag = false;

当node.element.attribute =“start”时,将此布尔值从false切换到true,然后当=“finish”完成时,返回false

相关问题