【问题标题】:Linq to xml for loop terminating early and unexpectedlyLinq to xml for 循环提前意外终止
【发布时间】:2012-10-16 13:13:27
【问题描述】:

我的 linq to xml foreach 循环提前意外终止。没有提出异常。怎么回事?


var doc = XDocument.Parse("<a><b>one</b><b>two</b></a>");

foreach(var element in doc.Root.Elements("b"))
{
 element.ReplaceWith(XElement.Parse("<c>fixed</c>"));
}

doc.Dump();

给我

<a>
  <c>fixed</c>
  <b>two</b>
</a>

当我预料到的时候

<a>
  <c>fixed</c>
  <c>fixed</c>
</a>

【问题讨论】:

    标签: c# .net xml linq linq-to-xml


    【解决方案1】:

    我的 linq to xml foreach 循环提前意外终止。怎么回事?

    当您在同一文档上迭代延迟评估的查询时,修改文档通常是个坏主意。在某些情况下它可能会起作用,但很难预测,而且我不知道这种行为是否被记录在案。 (想象一下,如果评估持续到“当前”元素,并且每次都询问它的下一个兄弟元素 - 当元素从文档中删除时不会再有任何结果!)

    如果你先实现查询,它可以正常工作:

    foreach(var element in doc.Root.Elements("b").ToList())
    {
        // Removed the pointless XElement.Parse call; it's cleaner just to create
        // an element with the data you want.
        element.ReplaceWith(new XElement("c", "fixed"));
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      相关资源
      最近更新 更多