Как правило, вы не можете изменять значение переменной, но вы можете перекрыть ее локальной переменной. То есть локальные переменные перекрывают глобальные в пределах области видимости локальных переменных. Пусть, например, я объявил переменную с именем movie (кинокартина):
<xsclass="underline" variable name="movie" select="'Mr. Blandings Builds His Dream House'"/>
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House" -->
.
.
.
Это элемент верхнего уровня, поэтому movie — глобальная переменная. Даже внутри шаблонов movie будет сохранять свое начальное значение, если не будет локальной переменной с таким же именем:
<xsclass="underline" variable name="movie" select="'Mr. Blandings Builds His Dream House'"/>
<!-- здесь $movie = "Mr Blandings Builds His Dream House'-->
<xsclass="underline" template match="entertainment">
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House'-->
.
.
.
Однако если вы объявите локальную переменную movie, в шаблоне эта версия перекроет глобальную переменную:
<xsclass="underline" variable name="movie" select="'Mr. Blandings Builds His Dream House'">
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House'-->
<xsclass="underline" template match="entertainment">
<!-- здесь $movie = Mr. Blandings Builds His Dream House"-->
<xsclass="underline" variable name="movie" select="'Goldfinger'"/>
<!-- здесь $movie = 'Goldfinger'-->
.
.
.
В этом случае мы перекрыли глобальную переменную при помощи глобальной. Заметьте, однако, что нельзя снова объявить одну и ту же переменную в одном шаблоне с целью попытаться изменить ее значение:
<xsclass="underline" variable name="movie" select="'Mr. Blandings Builds His Dream House'"/>
<!-- здесь $movie = Mr. Blandings Builds His Dream House"-->
<xsclass="underline" template match="entertainment">
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House"-->
<xsclass="underline" variable name="movie" select="'Goldfinger'"/>
<!-- здесь $movie = 'Goldfinger'-->
<xsclass="underline" variable name="movie" select="'Withnail and I'"/><!-- Запрещено -->
.
.
.
За пределами шаблона локальная переменная невидима, и movie содержит глобальное значение:
<xsclass="underline" variable name="movie" select="'Mr. Blandings Builds His Dream House'"/>
<!-- здесь $movie = 'Mr Bindings Builds His Dream House' -->
<xsclass="underline" template match="entertainment">
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House'-->
<xsclass="underline" variable name="movie" select="'Goldfinger'"/>
<!-- здесь $movie = 'Goldfinger'-->
<xsclass="underline" variable name="movie" select="'Withnail and I'"/><!-- Запрещено -->
</xsclass="underline" template>
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House'-->
.
.
.
Глобальные переменные тоже нельзя объявлять повторно:
<xsclass="underline" variable name="movie" select="'Mr. Blandings Builds His Dream House'"/>
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House'-->
<xsclass="underline" template match="entertainment">
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House"-->
<xsclass="underline" variable name="movie" select="'Goldfinger'"/>
<!-- здесь $movie = 'Goldfinger'-->
<xsclass="underline" variable name="movie" select="'Withnail and I'"/><!-- Запрещено -->
</xsclass="underline" template>
<!-- здесь $movie = 'Mr. Blandings Builds His Dream House'-->
<xsclass="underline" variable name="movie" select="'Goldfinger'"/><!-- Запрещено -->
Несмотря на все эти ограничения, вы можете менять значение переменной на каждом шаге цикла <xsclass="underline" for-each>, как мы увидим в следующем разделе.
Работа с переменными
Давайте рассмотрим примеры применения переменных. В следующем примере (листинг 9.1) я присваиваю переменной copyright сообщение об авторских правах и затем с ее помощью добавляю атрибут copyright во все элементы planets.xml.
Листинг 9.1. Применение переменной<?xml version="1.0"?>
<xsclass="underline" stylesheet version="1.1"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsclass="underline" output method="xml"/>
<xsclass="underline" variable name="copyright" select="'(c)2002 Starpowder Inc.'"/>
<xsclass="underline" template match="*">
<xsclass="underline" copy>
<xsclass="underline" attribute name="copyright">
<xsclass="underline" value-of select="$copyright"/>
</xsclass="underline" attribute>
<xsclass="underline" apply-templates/>
</xsclass="underline" copy>
</xsclass="underline" template>
</xsclass="underline" stylesheet>
Вот результирующий документ, дополненный атрибутами copyright
<?xml version="1.0" encoding="utf-8"?>
<PLANETS copyright="(c)2002 Starpowder Inc.">
<PLANET copyright="(c)2002 Starpowder Inc.">
<NAME copyright="(c)2002 Starpowder Inc.">Mercury</NAME>
<MASS copyright="(c)2002 Starpowder Inc.">.0553</MASS>
<DAY copyright="(с)2002 Starpowder Inc.">58.65</DAY>
<RADIUS copyright="(c)2002 Starpowder Inc.">1516</RADIUS>
<DENSITY copyright="(c)2002 Starpowder Inc.">.983</DENSITY>
<DISTANCE copyright="(с)2002 Starpowder Inc.">43.4</DISTANCE>
</PLANET>
<PLANET copyright="(c)2002 Starpowder Inc.">
<NAME copyright="(c)2002 Starpowder Inc.">Venus</NAME>
<MASS copyright="(c)2002 Starpowder Inc.">.815</MASS>
<DAY copyright="(с)2002 Starpowder Inc.">116.75</DAY>
<RADIUS copyright="(c)2002 Starpowder Inc.">3716</RADIUS>
<DENSITY copyright="(c)2002 Starpowder Inc.">.943</DENSITY>
<DISTANCE copyright="(c)2002 Starpowder Inc.">66.8</DISTANCE>
</PLANET>
.
.
.
Переменные зачастую удобны для хранения значении, зависимых от контекста, и мы сейчас рассмотрим еще один пример, о котором я упоминал в начале главы. В этом случае я преобразую planets.xml в новый документ, в котором для каждой планеты будет один элемент. Каждый из этих новых элементов будет содержать два элемента <SIBLINGPLANET>, содержащих планеты-братья текущей планеты — например, братьями Земли будут Венера и Меркурий: