องค์ประกอบ <xsl:variable> ของ XSLT

การกำหนดและการใช้งาน

<xsl:variable> องค์ประกอบใช้เพื่อประกาศตัวแปรท้องถิ่นหรือทั่วไป。

หมายเหตุ:ถ้าถูกประกาศเป็นองค์ประกอบระดับสูง ตัวแปรนั้นจะเป็นทั่วไป และถ้าถูกประกาศในโมดูล ตัวแปรนั้นจะเป็นท้องถิ่น。

หมายเหตุ:หากคุณได้ตั้งค่าค่าของตัวแปร คุณจะไม่สามารถเปลี่ยนแปลงหรือแก้ไขค่านั้นได้!

คำเตือน:คุณสามารถเพิ่มค่าให้ตัวแปรด้วยเนื้อหาของ <xsl:variable> หรือด้วยคุณสมบัติ select!

ภาษาเขียน

<xsl:variable
name="name"
select="expression">
  <!-- Content:template -->
</xsl:variable>

คุณสมบัติ

คุณสมบัติ ค่า คำอธิบาย
name name สำคัญต้องมี
select expression ในตอนนี้

ตัวอย่าง

ตัวอย่าง 1

ถ้าได้กำหนดคุณสมบัติ select ตัวแปร <xsl:variable> จะไม่สามารถมีเนื้อหาใดๆ ต่างหาก ถ้าคุณสมบัติ select มีข้อความตัวอักษร ต้องใส่ข้อความด้วยเครื่องหมายเปิดปิดเครื่องหมายของตัวอักษร:

ตัวอย่างสองตัวดังนี้ให้ค่าแก่ตัวแปร "color" ด้วยค่า "red":

<xsl:variable name="color" select="'red'" />
<xsl:variable name="color" select='"red"' />

ตัวอย่าง 2

ถ้า <xsl:variable> มีเพียงแค่คุณสมบัติ name และไม่มีเนื้อหา ตัวแปรจะมีค่าว่าง:

<xsl:variable name="j" />

ตัวอย่าง 3

ตัวอย่างดังนี้ใช้ <xsl:variable> ให้ค่าแก่ตัวแปร "header":

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="header">
  <tr>
  <th>Element</th>
  <th>รายละเอียด</th>
  </tr>
</xsl:variable>
<xsl:template match="/">
  <html>
  <body>
  <table>
    <xsl:copy-of select="$header" />
    <xsl:for-each select="reference/record">
    <tr>
    <xsl:if category="XML">
      <td><xsl:value-of select="element"/></td>
      <td><xsl:value-of select="description"/></td>
    </xsl:if>
    </tr>
    </xsl:for-each>
  </table>
  <br />
  <table>
    <xsl:copy-of select="$header" />
    <xsl:for-each select="table/record">
    <tr>
    <xsl:if category="XSL">
      <td><xsl:value-of select="element"/></td>
      <td><xsl:value-of select="description"/></td>
    </xsl:if>
    </tr>
    </xsl:for-each>
  </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>