【问题标题】:When I search under XPathNodeIterator.Current.SelectSingleNode, It simply searches in whole xml document当我在 XPathNodeIterator.Current.SelectSingleNode 下搜索时,它只是在整个 xml 文档中搜索
【发布时间】:2013-09-25 17:00:04
【问题描述】:

您好,我正在使用 XPathNodeIterator 在 XML 文档下的 XML 节点列表中进行迭代。如果条件匹配,则在迭代时,我需要该当前节点下的特定值。相反,SelectSingleNode 是从其他父节点返回节点...让我举个例子:

XPathNavigator SourceReqNav = // Load this using an xml;
XmlNamespaceManager manager = new XmlNamespaceManager(SourceReqNav.NameTable);
SourceReqNav.MoveToRoot();
XPathNodeIterator nodeIterator = SourceReqNav.Select(parentPath, manager);

while (nodeIterator.MoveNext())
{
 //If condition matches at nodeIterator.Current node, Executing a partial xpath related to   
 //only that current node

XPathNavigator singleNode = nodeIterator.Current.SelectSingleNode(xpath, namespaceManager);

// Here at above line, It should return null as Child node doesn't exist but It 
// searches in whole xml and finding the matching one..even though the XPATH is kind of
// partial and applicable to only that node structure.
}

示例 xml:

<RootNode>
 <Element id=1>
   <Address>
     <Name>      </Name>
     <ZipCode>456</ZipCode>
     <Street> </Street>
   </Address>
 </Element>
 <Element id=2>
 </Element>
 <Element id=3> </Element>
</RootNode>

假设,我正在迭代所有“元素”并试图找到元素 id=2 的“地址”。 现在,在迭代时假设我在“Element id=2”。当我找到节点时,我会说从当前节点(nodeIterator.Current)中选择一个名为“Zip”的节点。为此,我将 xpath 用作“/Address/ZipCode”(此处的格式可能是错误的,因为这只是示例)。在这种情况下,它应该返回 null,而是从“Element id=1”返回 ZipCode

任何帮助都会很明显..

【问题讨论】:

  • 我希望更多的人知道XElement 如何使用 LINQ。
  • 嗯,我确实使用 LINQ to XML。但这是更加可定制的框架工作的一部分,用户可以使用 XPATH(扩展)通过配置文件简单地更改映射。无论如何,这不是我要找的。感谢您花时间看一看。

标签: c# xpath xpathnavigator selectsinglenode xpathnodeiterator


【解决方案1】:

由于时间限制(为了修复),我走了更长的路线。 我没有直接在当前节点搜索,而是从当前节点获得了 SubTree(类型:XmlReader),并使用它加载了一个 XPathDocument。然后从它创建了一个 XPathNavigator。比对其应用相同的部分 XPath。

nodeIterator.Current.SelectSingleNode(xpath, namespaceManager);

修改为:

XmlReader sourceReader = nodeIterator.Current.ReadSubtree();
XPathDocument doc = new XPathDocument(sourceReader);
XPathNavigator sourceNavigator = doc.CreateNavigator();
sourceNavigator.SelectSingleNode(xpath, namespaceManager);

如果有人有更好的答案,我仍然想避免它。希望这会对某人有所帮助。

【讨论】:

  • 我知道这是超级旧的,但我也想要一个不创建另一个对象的解决方案。
猜你喜欢
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2015-06-01
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多