how to use key in xslt?

I am trying to search value in xml using key but I am not getting expected result here is my code http://xsltransform.net/6rewNyZ/1

  <xsl:key name="mid" match="parent_id" use="@id"/>
    <xsl:template match="/">
      <hmtl>
    <xsl:variable name="msid" select="'54'"/>
    <xsl:variable name="msids_map">
        <parent_id id="34">
          <childid>1</childid>
          <childid>2</childid>
        </parent_id>
        <parent_id id="54">
          <childid>3</childid>
          <childid>4</childid>
        </parent_id>
    </xsl:variable>
       <xsl:variable name ="abc" select="ext:node-set(msids_map)">
       </xsl:variable>
       <xsl:variable name="getValue" select=
        "key('mid', $abc)"/>

        <xsl:value-of select="$getValue"/> 

Expected output

<parent_id id="54">
              <childid>3</childid>
              <childid>4</childid>
            </parent_id>

Answers 1

  • You have a few minor syntax issues, and a major context issue. Keys operates in the context of the current document - which in your example is the input XML document. In order to get the key to operate on the variable (which is a document of its own), you must first switch the context - for example, by using xsl:for-each select="$abc"before calling the key.

    Here is a full example (with the syntax errors corrected, too):

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ext="http://exslt.org/common"
    extension-element-prefixes="ext">
    <xsl:output method="html" encoding="UTF-8"/>
    
    <xsl:key name="mid" match="parent_id" use="@id"/>
    
    <xsl:template match="/">
        <hmtl>
            <xsl:variable name="msid" select="'54'"/>
            <xsl:variable name="msids_map">
                <parent_id id="34">
                    <childid>1</childid>
                    <childid>2</childid>
                </parent_id>
                <parent_id id="54">
                    <childid>3</childid>
                    <childid>4</childid>
                </parent_id>
            </xsl:variable>
            <xsl:variable name ="abc" select="ext:node-set($msids_map)"/>
            <xsl:for-each select="$abc">
                <xsl:variable name="getValue" select="key('mid', $msid)"/>
                <xsl:copy-of select="$getValue"/>
            </xsl:for-each>
           </hmtl>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Demo: http://xsltransform.net/6rewNyZ/4


Related Articles