title: XSL Match Element based on a Value
body: <p>I am transforming an XML where I am supposed to locate a particular Element (based on the attribute value) and update the Element and its child attributes. </p>
  
  <p>The sample XML file is as below. </p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;Configuration&gt;
      &lt;Environments&gt;
          &lt;Environment id="Master"/&gt;
          &lt;Environment id="Developer"/&gt;
      &lt;/Environments&gt;
      &lt;Common&gt;
          &lt;Logging&gt;
              &lt;LogFile&gt;log\updater.log&lt;/LogFile&gt;
          &lt;/Logging&gt;
      &lt;/Common&gt;
  &lt;Configuration&gt;
  </code></pre>
  
  <p>My XSLT file is as below. </p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
  &gt;
      &lt;xsl:output method="xml" indent="yes"/&gt;
      &lt;xsl:param name="EnvironmentId" /&gt;
      &lt;xsl:param name="SelectEnvironment" /&gt;
      &lt;!-- Copy All Elements --&gt;
      &lt;xsl:template match="@* | node()"&gt;
          &lt;xsl:copy&gt;
              &lt;xsl:apply-templates select="@* | node()"/&gt;
          &lt;/xsl:copy&gt;
      &lt;/xsl:template&gt;
      &lt;!-- Modify Element with id = Developer--&gt;
      &lt;xsl:template match="Environment/@id[. ='Developer']"&gt;
          &lt;xsl:attribute name="id"&gt;
              &lt;xsl:value-of select="$EnvironmentId"/&gt;
          &lt;/xsl:attribute&gt;
      &lt;/xsl:template&gt;
  
  &lt;/xsl:stylesheet&gt;
  </code></pre>
  
  <p>In this XSLT, variable EnvironmentId contains the new id; variable SelectEnvironment should contain the value Developer (or any other user provided value passed via C#.NET)</p>
  
  <p><strong>Question</strong></p>
  
  <p>How do I write my XSLT so that the match works based on a user-defined value?</p>
  
  <p>I tried the following</p>
  
  <pre><code>&lt;xsl:template match="Environment/@id[. ='$SelectEnvironment']"&gt;
      &lt;xsl:attribute name="id"&gt;
          &lt;xsl:value-of select="$EnvironmentId"/&gt;
      &lt;/xsl:attribute&gt;
  &lt;/xsl:template&gt;
  </code></pre>
  
  <p>No errors. But, the attr id was not updated. </p>
  
  <p>I tried this...</p>
  
  <pre><code>&lt;xsl:template match="Environment/@id[. =$SelectEnvironment]"&gt;
      &lt;xsl:attribute name="id"&gt;
          &lt;xsl:value-of select="$EnvironmentId"/&gt;
      &lt;/xsl:attribute&gt;
  &lt;/xsl:template&gt;
  </code></pre>
  
  <p>And I got a run time error of Variables cannot be used within this expression. </p>