Ahmad February 2016

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.

Answers


kjhughes February 2016

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.

Post Status

Asked in February 2016
Viewed 1,066 times
Voted 10
Answered 1 times

Search




Leave an answer