Ahmad
Ahmad

Reputation: 9658

Select child of current node based on attribute value in XPath?

I have XML like

   ...
    <S head="X">
       <A head="X">
          <A1 head="Z">
          <A2 head="X">
       <B head="Y">
    </S>
   ...

I would like to select a child of S which has an attribute whose value is "X". (Note I know nothing about the names of elements S, A, B...)

I tried

string headTag = node.SelectSingleNode("//*[@head='X']").Name;

It returns "S", while I expect to get "A" if node points to S and "A2" if node points to A.

Upvotes: 2

Views: 1565

Answers (1)

kjhughes
kjhughes

Reputation: 111551

This XPath will select all of the child elements, regardless of name, with a @head attribute value equal to X:

./*[@head='X']

starting from the current node.

When the current node is S, it'll select A; when the current node is A, it'll select A2, all as requested.

Upvotes: 4

Related Questions