Sponsored

XSLT Reference

environment-variable()

XSLT 3.0 node function

Returns the value of the named environment variable as a string, or the empty sequence if unavailable.

Syntax
environment-variable(name)

Description

environment-variable() retrieves the value of a named operating-system or processor-defined environment variable. The function returns the value as a string if the variable is set and accessible, or the empty sequence if it is not available.

Processors are not required to expose any particular environment variables, and they may choose to expose none at all for security reasons. Use available-environment-variables() to discover which variables are accessible before calling this function. The function raises no error when a variable is absent — it simply returns the empty sequence, which can be tested with exists() or empty().

Parameters

ParameterTypeRequiredDescription
namexs:stringYesThe name of the environment variable to retrieve.

Return value

xs:string? — the value of the environment variable, or the empty sequence if the variable is not set or not accessible.

Examples

Using an environment variable as a default

Input XML:

<?xml version="1.0" encoding="UTF-8"?>
<config/>

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/config">
    <xsl:variable name="home" select="environment-variable('HOME')"/>
    <settings>
      <home><xsl:value-of select="($home, 'unknown')[1]"/></home>
      <user><xsl:value-of select="(environment-variable('USER'), 'anonymous')[1]"/></user>
    </settings>
  </xsl:template>
</xsl:stylesheet>

Output (on a Unix system):

<settings>
  <home>/home/username</home>
  <user>username</user>
</settings>

Checking availability before reading

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:choose>
      <xsl:when test="exists(environment-variable('APP_ENV'))">
        Environment: <xsl:value-of select="environment-variable('APP_ENV')"/>
      </xsl:when>
      <xsl:otherwise>
        APP_ENV not set — using defaults
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

Output:

APP_ENV not set — using defaults

Notes

  • Whether environment variables are accessible depends entirely on the processor implementation and security configuration. Saxon exposes OS environment variables by default, but this can be disabled.
  • The function is read-only; there is no mechanism in XPath/XSLT to set environment variables.
  • Environment variable names are case-sensitive on Unix-like systems and case-insensitive on Windows.
  • For production stylesheets, prefer XSLT parameters (xsl:param) over environment variables, as parameters are more portable and explicit.

See also