1
votes

I need to figure out a way to evaluate a count Xpath expression in C# .net. Currently I am looping through an XML document, and I end up on a particular node. I need to figure out which node that I am on at that point. The node is differentiated by an attribute that has a value.

    <A>
     <B>
      <C> 
       <D attr="10"/>
      </C>
      <C> 
       <D attr="10"/>
      </C>
      <C> 
       <D attr="11"/>
      </C>
      <C> 
       <D attr="10"/><!--Imagine I am here...  This would be the 3rd D attr that equals 10-->
      </C>
      <C> 
       <D attr="12"/>
      </C>
     </B>
    </A>

Let's say I am on the second I currently have an XMLDocument open. And I have selected a list of nodes... I am worried that If I open an XpathDocument I will lose my position in the xmlNode list. I guess I could get the attr value by using xpath and then use an XpathDocument and Evaluate that expression that way. I was hoping there might be an easier way.

thanks.

1
You should share the relevant C# code as well. Answering your question would be a lot easier. - Tomalak

1 Answers

1
votes

Use:

(int) (theDocument.CreateNavigator()
        .Evaluate("count(/A/B/C[D/@attr = 10][3]/preceding-sibling::C) +1"))

On the provided XML document the result is:

4