循环遍历XPathNodeIterator问题
我创建了一个 XPathNodeIterator,其中包含一些短的 XML 段(每个段都有一个文件描述):
XPathNodeIterator segments = node.SelectDescendants("Segment", node.NamespaceURI, false);
现在,当尝试循环它们时,似乎每次都只选择第一个段。以下是我尝试过的循环的两个版本(仅以文件/文件类为例):
while (segments.MoveNext())
{
File f = GetSingleFileDataFromSegment(segments.Current);
files.Add(f);
}
另一种尝试:
foreach (XPathNavigator seg in segments)
{
File f = GetSingleFileDataFromSegment(seg);
files.Add(f);
}
当使用 Watch 或 Quickwatch 查看循环中的单个片段时,它看起来应该如此,所有不同的片段都在一次 - 但最终结果是“文件”包含第一个段的多个副本。
这是 XPathNodeIterator 的正常行为吗?或者这里缺少什么?我目前正在使用 .NET Framework 3.5。
I've created a XPathNodeIterator that contains a few short XML segments (each with a file description):
XPathNodeIterator segments = node.SelectDescendants("Segment", node.NamespaceURI, false);
Now, when trying to loop them, it seems that only the first segment is picked every time. Here are two versions of the loops I've tried (File/Files classes only for example):
while (segments.MoveNext())
{
File f = GetSingleFileDataFromSegment(segments.Current);
files.Add(f);
}
Another try:
foreach (XPathNavigator seg in segments)
{
File f = GetSingleFileDataFromSegment(seg);
files.Add(f);
}
When viewing a single segment in a loop with Watch or Quickwatch, it looks as it should, all different segments are selected one at a time - but end result is that "files" contain multiple copies of the first segment.
Is this normal behavior with XPathNodeIterator? Or is something missing here? I'm currently using .NET Framework 3.5.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在 GetSingleFileDataFromSegment 方法中,该方法使用 XPath 来获取正确的段。段属性中包含命名空间,这需要使用命名空间管理器。
有错误的 XPath 表达式:
更正版本:
上面的代码位于接收段作为参数的方法中。
The problem was in GetSingleFileDataFromSegment -method, which used XPath to get the proper segment. The segment attributes had namespaces in them, and that required the use of a NamespaceManager.
Faulty XPath expression:
Corrected version:
Code above was in the method that received the segment as parameter.