0

I'm trying to get the nth occurence of an element C in my XML (across different parents)

Input:

<TEST>
<A>
    <B>*</B>
    <C>Text1</C> (#1)
</A>
<A>
    <B>*</B>
</A>
<A>
    <B>/</B>
    <C>Aaaa</C> (#2)
</A>
<A>
    <B>/</B>
    <C>Text2</C> (#3)
</A>
</TEST>

Desired result: get 2nd Element would yield "Aaaa"

I tried:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:sch="http://sap.com/xi/ME" xmlns:me="http://sap.com/xi/ME" xmlns:gdt="http://sap.com/xi/SAPGlobal/GDT" xmlns:meint="http://sap.com/xi/MEINT" xmlns:demand="http://www.sap.com/me/demand" xmlns:common="http://www.sap.com/me/common">
<xsl:template match="/">
        <xsl:value-of select="/TEST/A/descendant::C[2]"/>        
</xsl:template>
</xsl:stylesheet>

How do I get this to work?

Found this example but I can't get it to work: https://stackoverflow.com/a/25280116

Thank you

noIdeaAtAll
  • 123
  • 6

2 Answers2

0

Your attempt does not work because the 1st A element does not have a 2nd C descendant.

To select the 2nd C element in the entire document, try:

<xsl:value-of select="/descendant::C[2]"/>

or (same thing):

<xsl:value-of select="(//C)[2]"/>

To restrict the selection to C elements that are within the given hierarchy, you can do:

<xsl:value-of select="(/TEST/A/C)[2]"/>
michael.hor257k
  • 96,733
  • 5
  • 30
  • 46
0

I found the solution (notice the parenthesis):

<xsl:value-of select="(/TEST/A/descendant::C)[2]"/>     

For an explanation see: https://stackoverflow.com/a/4008925

noIdeaAtAll
  • 123
  • 6