1

I've the below type of XML structure

<root>
    <Section>
     <A></A>
     <B></B>
     <A></A>
    </Section>
    <Section>
     <A></A>
     <B></B>
     <A></A>
    </section>
   </root>

Here under each section there are 2 tags namely A and B but also there are 2 A nodes, Here i want to check with XPATH(XSLT2.0) if there are any preceding A under same Section, when i used Preceding::A, it is selecting everything i.e. it is not checking if it is in the same section or in different, but it is checking if there is a preceding A, but i want to check for preceding A in same Section, please let me know how can i do this.

Thanks

user3872094
  • 3,269
  • 8
  • 33
  • 71

2 Answers2

1

I think you simply want to check preceding-sibling::A.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
  • 1
    doesn't this mean that there should be `A` just before the current `A`, without any other nodes(here `B`) in between? – user3872094 Jul 31 '14 at 10:44
  • 1
    No, `preceding-sibling::A` checks whether there is any `A` element on the preceding sibling axis. You might want to try to read an XPath tutorial: http://www.xmlplease.com/axis – Martin Honnen Jul 31 '14 at 10:46
0

If the A elements are all siblings then Martin's suggestion of preceding-sibling::A is the simplest one. Alternatively you can let the template matcher do the work for you if you define separate templates for the first and subsequent A elements

<xsl:template match="A[1]">
  <!-- fires for the first A in each section -->
</xsl:template>

<xsl:template match="A">
  <!-- fires for A elements other than the first one -->
</xsl:template>

If the A elements can be at different levels, e.g.

<root>
 <Section>
  <A></A>
  <B></B>
  <A></A>
 </Section>
 <Section>
  <A></A>
  <B><A/></B>
  <C><A></A></C>
 </Section>
</root>

then you will need to be a bit more creative with the filtering. In "document order" a child element is considered to be after its parent so you could do something like

preceding::A[. >> current()/ancestor::Section[1]]

(i.e. all the preceding A elements that follow the current node's nearest Section ancestor in document order).

Community
  • 1
  • 1
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183