Search code examples
xsltxpathxslt-2.0

Transforming attribute values based on a dictionary encoded as a tree variable


It should be apparent what I'm trying to achieve looking at these sample files:

Input:

<root>
    <node type="A"/>
    <node type="B"/>
</root>

Stylesheet:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:variable name="fixes">
        <fix from="A" to="AA"/>
        <fix from="B" to="BB"/>
    </xsl:variable>

    <xsl:template match="@type[string()=$fixes/fix/@from]">
        <xsl:attribute name="type">
                <xsl:value-of select="$fixes/fix[@from=self::node()]/@to"/>
        </xsl:attribute>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Expected output:

<root>
    <node type="AA"/>
    <node type="BB"/>
</root>

Actual output (using saxon9he):

<root>
    <node type=""/>
    <node type=""/>
</root>

Any idea what I'm doing wrong?


Solution

  • Replace self::node() with current() to select the @type attribute matched on (and not the context node of the predicate, which is a fix element).

    In general for such tasks I would suggest to define a key

    <xsl:key name="fix" match="fix" use="@from"/>
    

    and then rewrite

    as

    <xsl:template match="@type[key('fix', ., $fixes)]">
      <xsl:attribute name="{name()}" select="key('fix', ., $fixes)/@to"/>
    </xsl:template>