$referenceName
không phải là tham chiếu đến biến có tên "unumericValue" hoặc cách khác. Nó chỉ là giá trị chuỗi "unumericValue", v.v. Vì vậy, nó sẽ không bao giờ lớn hơn $min
. Tuy nhiên, với một chút công việc khác, có một mẹo để tìm biến theo tên của nó:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="numericValue" select="10" />
<xsl:variable name="anotherValue" select="8" />
<xsl:variable name="vars" select="document('')/*/xsl:variable" />
<xsl:template match="/">
<xsl:variable name="referenceName" select="'numericValue'" />
<xsl:variable name="referenceValue" select="$vars[@name = $referenceName]/@select" />
Reference value: <xsl:value-of select="$referenceValue" />
</xsl:template>
</xsl:stylesheet>
Một hạn chế lớn cần lưu ý ở đây là chỉ làm việc cho các biến là giá trị số không đổi.
Đây là một cách để mô phỏng các biến với các giá trị chuỗi liên tục:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:v="variables-node"
>
<v:variables>
<v:variable n="numericValue" value="10" />
<v:variable n="nonNumericValue" value="Hello World" />
</v:variables>
<xsl:variable name="vars" select="document('')//v:variables/v:variable" />
<xsl:template match="/">
<xsl:variable name="referenceName" select="'nonNumericValue'" />
<xsl:variable name="referenceValue" select="$vars[@n = $referenceName]/@value" />
<xsl:value-of select="concat('The variable with the name ', $referenceName, ' has the value ', $referenceValue)"/>
</xsl:template>
</xsl:stylesheet>
Và cuối cùng, một cách để mô phỏng các biến với các giá trị tính toán:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exslt="http://exslt.org/common"
>
<xsl:variable name="varsRaw">
<var n="computedValue" value="{concat('2 + 4 is ', 2 + 4)}" />
<var n="computedNumber" value="{22 div 7}" />
</xsl:variable>
<xsl:variable name="vars" select="exslt:node-set($varsRaw)/var" />
<xsl:template match="/">
<xsl:variable name="referenceName" select="'computedValue'" />
<xsl:variable name="referenceValue" select="$vars[@n = $referenceName]/@value" />
<xsl:value-of select="concat('The variable with the name ', $referenceName, ' has the value ', $referenceValue)"/>
<xsl:value-of select="' '"/>
<xsl:variable name="referenceName2" select="'computedNumber'" />
<xsl:variable name="referenceValue2" select="$vars[@n = $referenceName2]/@value" />
<xsl:value-of select="concat('The variable with the name ', $referenceName2, ' has the value ', $referenceValue2)"/>
</xsl:template>
</xsl:stylesheet>
Phương pháp cuối cùng có lẽ là thực sự là chính thống nhất , nhưng yêu cầu chức năng phụ thuộc vào bộ xử lý XSLT (ít nhất là trong XSLT 1.0) node-set()
.
Cảm ơn rất nhiều. Đề nghị đầu tiên làm việc tuyệt vời cho tôi. – eadrax