问题描述
是否可以使用 XSL 访问名称存储在另一个变量(或参数)中的变量(或参数)?如果没有,为什么?
Is it possible using XSL to access a variable (or a parameter) whose name is stored in another variable (or parameter)? If no, why?
我是 xsl 的新手,来自其他语言,可以访问此功能,如 bash、ant.也许我什至在寻找这个问题的答案也是错误的.但是因为我没有在SO上找到它,所以我认为应该有一个.
I am new to xsl, coming from other languages, where this functionality is accessible, like bash, ant. Maybe I was wrong even looking for an answer to this question. But since I didn't find it on SO, I think there should be one.
两个例子.我有参数 p1
、p2
、p3
.然后我有一个参数pname
,它的值是一个字符串p2
.我想使用 pname
读取 p2
的值,例如 $$pname
或 ${$pname}
>.或者以更复杂的方式.如果 pnumber
等于 2
,那么我想读取名称为 concat('p', $pnumber)
的参数的值,我会编码为param-value(concat('p', $pnumber))
.
Two examples. I have parameters p1
, p2
, p3
. Then I have a parameter pname
whose value is a string p2
. I would like to read the value of p2
using pname
, something like $$pname
or ${$pname}
. Or in a more complicated way. If pnumber
is equal to 2
, then I would like to read the value of the parameter with name concat('p', $pnumber)
, something I would code asparam-value(concat('p', $pnumber))
.
推荐答案
当 XSLT 样式表将自身作为常规 XML 文档访问时,这是可能的:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:param name="p1" select="'P1-Value'"/>
<xsl:param name="p2" select="'P2-Value'"/>
<xsl:param name="p3" select="'P3-Value'"/>
<xsl:param name="pName" select="'p3'"/>
<xsl:param name="pNumber" select="2"/>
<xsl:variable name="vDoc" select="document('')"/>
<xsl:template match="/">
<xsl:value-of select=
"concat('Param with name ',
$pName,
' has value: ',
$vDoc/*/xsl:param[@name = $pName]/@select
)"/>
<xsl:text>
</xsl:text>
<xsl:variable name="vParam" select=
"$vDoc/*/xsl:param[@name = concat('p', $pNumber)]"/>
<xsl:value-of select=
"concat('Param with name p',
$pNumber,
' has value: ',
$vParam/@select
)"/>
</xsl:template>
</xsl:stylesheet>
产生想要的结果:
Param with name p3 has value: 'P3-Value'
Param with name p2 has value: 'P2-Value'
说明:
表达式 document('')
选择当前 XSLT 样式表的文档节点.
The expression document('')
selects the document node of the current XSLT stylesheet.
一个限制是当前的 XSLT 样式表必须具有(可通过)一个 URI(例如驻留在给定的文件中并可以通过其文件名访问)——如果样式表是动态生成(内存中的字符串).
A limitation is that the current XSLT stylesheet must have (be accessible via) a URI (such as residing at a given file and accessible by its filename) -- the above code doesn't produce a correct result if the stylesheet is dynamically generated (a string in memory).
这篇关于间接变量/参数引用(另一个属性中的名称/另一个变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!