Use xsl:key to link nodes in input XML document

In a previous post, I've described how you can use local variables and XPath expressions to link elements in the input XML document. An even better (and probably faster) alternative is to use the XSL keys. For example, you might want to link the target element with the source element in an XML document based on the ref attribute of the source and the id/@num attribute of the target:
<data>
  <source id="abc" ref="123" />
 
  <target>
     <text>Message</text>
     <id num="123" />
  </target>
</data>
You can define a key that will select the target element or another one that will select the text child of the target element (in which case you have to be a bit more creative in the use part of xsl:key definition):
<xsl:key name="target" match="target" use="id/@num" />
<xsl:key name="ttext" match="target/text" use="../id/@num" />
Assuming you want to display the text child of the target node, you could use either key in your transformation. If you use the target key, it returns the target node, so you have to continue with the XPath expression to get its text child; using the ttext key gives you the text node immediately:
<xsl:template match="source">
  <xsl:variable name="target" select="@target" />
  Source <xsl:value-of select="@id" />
    target <xsl:value-of select="key('target',@target)/text" />
    ttext <xsl:value-of select="key('ttext',@target)" />
</xsl:template>

No comments:

Post a Comment