当我在XPathNodeIterator.Current.SelectSingleNode下搜索时,它只搜索整个xml文档

时间:2013-09-25 17:00:04

标签: c# xpath xpathnavigator selectsinglenode xpathnodeiterator

您好我正在使用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,但它返回ZipCode“Element id = 1”

任何帮助都会很明显......

1 个答案:

答案 0 :(得分:0)

由于时间限制(对于修复),我采取了更长的路线。 我没有直接在Current Node上搜索,而是从Current节点获得了SubTree(Type: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);

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