Search code examples
xmlxsltxslt-2.0

XSLT - Looking for variable elements in for-each loops


I have a single XML document that I'm transforming into multiple HTML documents. The problem is that for each document generated I need to look up a different node in a separate collection of XML files.

Imagine my XML looks like this:

<index>
  <item>
    <species>Dog</species>
    <tagName>canine</tagName>
  </item>
  <item>
    <species>Cat</species>
    <tagName>feline</tagName>
  </item>
<index>

I have a collection of dozens of files that have elements called 'canine' and 'feline' scattered throughout. I need to call in the right one for each document.

My XSLT looks like this:

<xsl:template match="/">
  <xsl:for-each select="index/item">
    <xsl:result-document method="xml" href="{species}.html">
      <xsl:for-each select="collection('index.xml')//canine">
        <xsl:value-of select=".">
      </xsl:for-each>
    </xsl:result-document>
  </xsl:for-each>
</xsl:template>

I'm looking for a way to turn that "//canine" into a variable so that in the Dog document it looks for <canine>, in the Cat document it looks for <feline> etc etc.

I can't work out how to do it. Can anyone point me in the right direction? I've been messing about with variables, but I can't hit on anything that works.


Solution

  • I'm looking for a way to turn that "//canine" into a variable so that in the Dog document it looks for <canine>, in the Cat document it looks for <feline> etc etc.

    Try something like:

    <xsl:for-each select="collection('index.xml')//*[name()=current()/tagName]">
    

    Note:

    1. It would be better to use a key to select the elements by name - but apparently you cannot do that when your target is a collection (?);
    2. I am not sure your collection is defined correctly. But that would be a topic for another question.