atif
atif

Reputation: 1147

first child node name in xslt

I wanted to know how to find the first child node name of a specific node in xslt.

I have an xml:

 <name>
    <body>
      <para>
        <text> some text</text>
      </para>
    </body>
  </name>

Can i get a name using body/node()[1]/local-name()?

<xsl:template match="name">
<name> 
<xsl:variable name="firstchild" select="body/node()[1]/local-name()">
                        </xsl:variable>
 <xsl:value-of select="$firstchild" />
 </name>
</xsl:template>

The output should be

 <name>
    para
  </name> 

Upvotes: 6

Views: 13801

Answers (1)

freefaller
freefaller

Reputation: 19953

Try something like this...

<xsl:template match="name">
  <name>
  <xsl:variable name="firstchild" select="name(body/*[1])"/>
  <xsl:value-of select="$firstchild" />
  </name>
</xsl:template>

Or if you don't actually need the variable, just simply...

<xsl:template match="name">
  <name>
  <xsl:value-of select="name(body/*[1])" />
  </name>
</xsl:template>

Here is an xmlplayground of the 2nd example... to see the <name>para</name> click on the View Source in the output window.

Upvotes: 7

Related Questions