Выбрать главу

• substring-before(string string1, string string2). Возвращает часть строки string1 до первого вхождения строки string2;

• translate(string string1, string string2, string string3). Возвращает строку string1, в которой все вхождения символов в строке string2 заменены на соответствующие символы в строке string3.

В листинге 7.1 я ищу слово «miles» во всех атрибутах, и если оно встречается, добавляю в результирующий документ текст «You should switch to kilometers.» (Нужно перевести в километры.).

Листинг 7.1. Поиск текста в атрибутах

<?xml version="1.0"?>

<xsclass="underline" stylesheet version="1.0"

 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsclass="underline" template match="/PLANETS">

  <HTML>

   <HEAD>

    <TITLE>

     The Planets Table

    </TITLE>

   </HEAD>

   <BODY>

    <H1>

     The Planets Table

    </H1>

    <TABLE BORDER="2">

     <TR>

      <TD>Name</TD>

      <TD>Mass</TD>

      <TD>Radius</TD>

      <TD>Day</TD>

      <TD>Distance</TD>

     </TR>

     <xsclass="underline" apply-templates/>

    </TABLE>

   </BODY>

  </HTML>

 </xsclass="underline" template>

 <xsclass="underline" template match="PLANET">

  <TR>

   <TD><xsclass="underline" value-of select="NAME"/></TD>

   <TD><xsclass="underline" apply-templates select="MASS/></TD>

   <TD><xsclass="underline" apply-templates select="RADIUS"/></TD>

   <TD><xsclass="underline" apply-templates select="DAY"/></TD>

   <TD><xsclass="underline" apply-templates select="DISTANCE"/></TD>

  </TR>

 </xsclass="underline" template>

 <xsclass="underline" template match="MASS">

  <xsclass="underline" value-of select="."/>

  <xsclass="underline" text> </xsclass="underline" text>

  <xsclass="underline" value-of select="@UNITS"/>

 </xsclass="underline" template>

 <xsclass="underline" template match="RADIUS">

  <xsclass="underline" value-of select="."/>

  <xsclass="underline" text> </xsclass="underline" text>

  <xsclass="underline" value-of select="@UNITS"/>

 </xsclass="underline" template>

 <xsclass="underline" template match="DAY">

  <xsclass="underline" value-of select="."/>

  <xsclass="underline" text> </xsclass="underline" text>

  <xsclass="underline" value-of select="@UNITS"/>

 </xsclass="underline" template>

 <xsclass="underline" template match="DISTANCE">

  <xsclass="underline" value-of select="."/>

  <xsclass="underline" text> </xsclass="underline" text>

  <xsclass="underline" value-of select="@UNITS"/>

 </xsclass="underline" template>

 <xsclass="underline" template match="//*[contains(@UNITS, 'miles')]">

  <xsclass="underline" value-of select="."/>

  <xsclass="underline" text> </xsclass="underline" text>

  <xsclass="underline" text>You should switch to kilometers.</xsclass="underline" text>

 </xsclass="underline" template>

</xsclass="underline" stylesheet>

Вот результирующий документ:

<HTML>

 <HEAD>

  <TITLE>

   The Planets Table

  </TITLE>

 </HEAD>

 <BODY>

  <H1>

   The Planets Table

  </H1>

  <TABLE BORDER="2">

   <TR>

    <TD>Name</TD>

    <TD>Mass</TD>

    <TD>Radius</TD>

    <TD>Day</TD>

    <TD>Distance</TD>

   </TR>

   <TR>

    <TD>Mercury</TD>

    <TD>.0553 (Earth = 1)</TD>

    <TD>1516 You should switch to kilometers.</TD>

    <TD>58.65 days</TD>

    <TD>43.4 You should switch to kilometers.</TD>

   </TR>

   <TR>

    <TD>Venus</TD>

    <TD>.815 (Earth = 1)</TD>

    <TD>3716 You should switch to kilometers.</TD>

    <TD>116.75 days</TD>

    <TD>66.8 You should switch to kilometers.</TD>

   </TR>

   <TR>

    <TD>Earth</TD>

    <TD>1 (Earth = 1)</TD>

    <TD>2107 You should switch to kilometers.</TD>

    <TD>1 days</TD>

    <TD>128.4 You should switch to kilometers.</TD>

   </TR>

  </TABLE>

 </BODY>

</HTML>

Помимо работы с наборами узлов, числами и строками, можно работать и с логическими значениями (true/false).

Логические значения XPath

Логические (Boolean) выражения XPath вычисляются либо в истину (true), либо в ложь (false), и обычно они используются только в предикатах. Для чисел ноль принимается за ложь, другие значения — за истину. Пустая строка, "", также считается ложью, все остальные строки — истиной.

Для генерации логических результатов true/false в XPath можно применять ряд логических операций, как мы видели в обзоре в главе 4:

• != означает «не равно»;

• < означает «меньше, чем» (в документах XML используйте <);

• <= означает «меньше или равно» (в документах XML используйте <=);

• = означает «равно» (программисты на С, С++, Java и JavaScript, обратите внимание: эта операция пишется как один знак =, а не два);

• > означает «больше, чем»;

• >= означает «больше или равно».

Для связи логических выражений логическими операциями And и Or используются ключевые слова and и or, слово not инвертирует логический смысл выражения, как в следующем примере, где я выбираю все элементы <PLANET>, кроме первого и последнего:

<xsclass="underline" template match="PLANET[not(position() = 1) and not(position() = last())]">

 <xsclass="underline" value-of select="."/>

</xsclass="underline" template>

Следующий пример уже встречался нам в главе 5, он использует логическую операцию not и операции = и !=:

<xsclass="underline" template match="PLANET">

 <xsclass="underline" if test="NAME[not(text())]">