Karan Parikh
Karan Parikh

Reputation: 321

Extracting the current XPath of the node from XPathIterator C#

I am writing a C# function where I need to fetch the value of a node using Xpath and if the fetched values matches a given string, I need to pass the Xpath to an API which replaces the current value of the node with value stored in Database.

The problem is there are multiple matches for the given Xpath, I filter those out with the string matching criteria and am able to figure out the node, however, I am not getting how to capture the exact Xpath of matching node and pass it to the API for it to work.

Lets take this XML as an example

<GrandParent>
  <Parent>
    <Child1>John
    </Child1>
    <Child2>Emily
    </Child2>
  </Parent>
  <Parent>
    <Child1>Frank
    </Child1>
    <Child2>Niki
    </Child2>
  </Parent>
  <Parent>
    <Child1>Mia
    </Child1>
    <Child2>Noah
    </Child2>
  </Parent>
</GrandParent>

Now I will have to fetch the node with Xpath /GrandParent/Parent/Child1 whose value would be John.

I am doing that in C# using XPathNavigator and XPathIterator

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(requestXML);

            XPathNavigator nav;
            nav = xmlDoc.CreateNavigator();

            XPathNodeIterator allMatchingNodes = nav.Select(SourceXPath);

            int countNodes = 1;

            foreach (XPathNavigator node in allMatchingNodes)
            {
                if(node.Value.Equals("John"))
                {
                  Xpath = SourceXPath + "[" + countNodes + "]";
                  break;
                }
                    
            }

However, this would be an incorrect approach as it will create xpath as /GrandParent/Parent/Child1[1] and hence the subsequeent API replaces is incorrectly.

I would want xpath as /GrandParent/Parent[1]/Child1 is there someway of doing that without using multiple foreach?

Upvotes: 0

Views: 46

Answers (0)

Related Questions