Chris Warner
Chris Warner

Reputation: 33

Finding the first Preceding Sibling with a particular element

Given The following XML:

<Root>
  <NodeA>
    <ChildNodeA/>
    <ChildNodeB/>
  </NodeA>
  <NodeB>
    <ChildNodeB/>
  </NodeB>
  <NodeC>
  </NodeC>
</Root>

How do I find the first Preceding Siblilng of a particular Node that contains a particular Element.

I.E. If I am at "NodeC" how do I find the first Sibling with "ChildNodeA", in this instance "NodeA"?

Thanks in advance.

Upvotes: 3

Views: 3004

Answers (1)

Tim C
Tim C

Reputation: 70648

To find the first preceding sibling that contains a child element is quite straight-forward, and indeed closely matches the way you describe it....

<xsl:apply-templates select="preceding-sibling::*[ChildNodeA][1]" />

Assuming your were positioned on NodeC, this would indeed return your NodeA in your case

<NodeA>
  <ChildNodeA></ChildNodeA>
  <ChildNodeB></ChildNodeB>
</NodeA>

Upvotes: 4

Related Questions