0
votes

I have an xml file where a section is defined for environment. I'd like to have the XSLT contain a key/value pair that would override those values. for example:

Sample INPUT XML - YES, variable is nested

<root>
<folders/>
<variables>
  <variable>
    <name>homeserver</name>
    <value>myServer.com</value>
    <variable>
    <name>workserver</name>
    <value>work.com</value>
    </variable>
    </variable>
</variables>
</root>

Sample XLST in meta code:

<xsl:variable name=KeyPair>
  <environment>
    <item name="homeserver" value="testhomeserver.com">
    <item name="workserver" value="testworkserver.com">
</xsl:variable>

<xsl:magic happens here />

Intended output:

<root>
<folders/>
<variables>
  <variable>
    <name>homeserver</name>
    <value>testhomeserver.com</value>
    <variable>
    <name>workserver</name>
    <value>testworkserver.com</value>
    </variable>
    </variable>
</variables>
</root>
1

1 Answers

0
votes

This is not easy to do in XSLT 1.0 because (1) variables are not node-sets, and (2) you cannot use keys here.

Anyway, I suggest you start with an identity template to copy everything as is, then add another template to match the values that need replacing:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">

<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:variable name="KeyPair">
    <item name="homeserver" value="testhomeserver.com"/>
    <item name="workserver" value="testworkserver.com"/>
</xsl:variable>
<xsl:variable name="KeyPairSet" select="exsl:node-set($KeyPair)" />

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

<xsl:template match="value">
    <xsl:if test="preceding-sibling::name[1]=$KeyPairSet/item/@name">
        <xsl:copy>
            <xsl:value-of select="$KeyPairSet/item[@name=current()/preceding-sibling::name[1]]/@value" />
        </xsl:copy>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>