Search code examples
xmlxsltxslt-1.0

How to select elements from an xml variable in xslt-1.0?


I have here an xslt transform, including this:

<xsl:variable name="mydict">
  <dict>
    <entry name="a" value="1"/>
    <entry name="b" value="2"/>
    <entry name="c" value="3"/>
    <entry name="d" value="4"/>
  </dict>
</xsl:variable>

That works, I can refer it as $mydict and, for example, print it with an <xsl:copy-of select="$mydict"/>.

However, things are becoming ugly from the moment if I want to actually use it for something, more clearly if I want to use it as a dictionary. Or map. Or string-indexed string-array.

How can I get, for example, 3 if I have another variable with value "c"?

My tries with $mydict//entry[@name="$c"] and similars all failed with various symptoms. I think, problem might root in that $mydict is like a string and not a node, in which I could do various operations (most importantly, refering its parts by xpath queries).

I have here an xsltproc command line tool and I would be happy to remain by it, but a switch to the latest saxon is possible if there is no better way.


Solution

  • As others have commented your variable holds a result tree fragment (RTF), not a node set.

    In XSLT 1.0, without a node-set() extension, the document function can access the RTF due to the fact that XSL is also XML, e.g.

    <xsl:variable name="de" select="document('')/*/xsl:variable[@name='mydict']/dict/entry"/>
    <xsl:value-of select="$de[@name='c']/@value"/>
    

    Alternatively, data islands in the stylesheet can be used with key(), like this.