Linq到XML for循环终止和意外(Linq to xml for loop terminating early and unexpectedly)

编程入门 行业动态 更新时间:2024-10-22 10:40:37
Linq到XML for循环终止和意外(Linq to xml for loop terminating early and unexpectedly)

我的LINQ到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>

My linq to xml foreach loop is terminating early and unexpectedly. No exception raised. What's going on?


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();

Gives me

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

When I expected

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

最满意答案

我的LINQ到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")); }

My linq to xml foreach loop is terminating early and unexpectedly. What's going on?

It's generally a bad idea to modify the document when you're iterating over a lazily evaluated query on the same document. In some cases it may work, but it's hard to predict, and I don't know whether the behaviour is even documented. (Imagine if the evaluation holds on to the "current" element, and asks it for its next sibling each time - there won't be any more results when the element has been removed from the document!)

If you materialize the query first, it works fine:

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")); }

更多推荐

本文发布于:2023-08-06 17:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1453834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意外   xml   Linq   XML   early

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!