unwellmilles
unwellmilles

Reputation: 45

Save the result of the key function in a variable

I want to save a node obtained from a key in a variable. This in order to access to the node attributes later with something like this: $variable/@attribute, but this syntax doesn't work.

my input.xml

<?xml version = '1.0' encoding = 'UTF-8' ?>

<tag1>
 <tag2 id = '866' name = 't1' />
 <tag2 id = '867' name = 't2' />
 <tag2 id = '868' name = 't3' />
</tag1>

my template.xsl

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:cms="http://www.ametys.org/schema/cms"
            xmlns:UML="org.omg.xmi.namespace.UML"
            exclude-result-prefixes="cms UML">

<xsl:key name="k" match="/tag1/tag2" use="@id"/>

 <xsl:template match="/">

  <xsl:variable name="linkedClassName">
    <xsl:for-each select="key('k', '866')">
      <xsl:value-of select="."/>
     </xsl:foreach>  </xsl:variable>

         RESULT:  <xsl:value-of select="$linkedClassName/@name" />
         RESULT2: <xsl:value-of select="key('k','866')/@name"/>

 </xsl:template>

</xsl:stylesheet>

my output.xml

<?xml version="1.0" encoding="UTF-8"?>
 RESULT:
 RESULT2:  t1

The RESULT line is what I want to do but as you can see it doesn't worK.

The RESULT line is what I want to do but as you can see it doesn't work. The RESULT2 line is the only alternative that I found, but It means call the key function (which is very slow) each time I need to access to one of the node's attribute.

Upvotes: 0

Views: 216

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Use <xsl:variable name="v1" select="key('k', '866')"/>, then <xsl:value-of select="$v1/@name"/>.

Upvotes: 2

Related Questions