1

Hi I'm iterating in a list of XML nodes under an XML document using XPathNodeIterator. While iterating if condition matches, I need particular value under that current node. Instead, SelectSingleNode is returning node from other parent node...Let me give an example:

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.
}

Sample xml:

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

Let's say, I'm iterating to all 'Element' and trying to find "Address" where element id=2. Now, while iterating let's say I'm at "Element id=2". As I found node, I'll say from the current node (nodeIterator.Current) select a single node called "Zip". For that, I'm using xpath as "/Address/ZipCode" (formatting might be wrong here as this is just for example). In this case, It should return me null, but instead it returns ZipCode from "Element id=1"

Any help would be appreciable..

Reg
  • 21
  • 2
  • 1
    I wish more people knew about `XElement` how you can use LINQ with it. – gunr2171 Sep 25 '13 at 17:10
  • Well, I do use LINQ to XML. But this was a part of much more customizable framework effort where user can simply change the mapping through config files using XPATH (extended). Anyway, that's not what I'm looking for. I appreciate the time you took to take a look. – Reg Sep 25 '13 at 17:52

1 Answers1

1

Due to time constraint (for the fix), I took little longer route. Instead of searching directly at Current Node, I got SubTree (Type: XmlReader) from Current node and by using it loaded an XPathDocument. Than created an XPathNavigator from it. Than applied same partial XPath on it.

nodeIterator.Current.SelectSingleNode(xpath, namespaceManager);

This was modified to:

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

I would still like to avoid it if someone has better answer. Hope this will help someone.

Reg
  • 21
  • 2