从动态变量填充节点
问题描述:
我想要在输出文档(输入可以是任何东西)内的根标签下的节点a中获得值“a”。我知道如果我做从动态变量填充节点
<xsl:value-of select="$item1"/>
我会得到所需的值。但是我想使用类似
<xsl:value-of select="concat('$item','1')"/>
的原因是因为我可以有许多变量创建动态,并在变量的末尾数被递增。所以我可以有item1,item2,item3等。我在这里展示了一个示例,这就是为什么我在select的值中使用硬编码值'1'。这可能在xslt1.0中吗?
这是我的XSLT,任何输入XML可以用来
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:variable name="item1" select="'a'" />
<Root>
<a>
<xsl:value-of select="concat('$item','1')"/>
</a>
</Root>
</xsl:template>
</xsl:stylesheet>
答
PHP等变量变量是不可能在XSLT 1.0/1.0的XPath。
通过使用exslt
-extension的node-set()
函数,可以构建一个像数组一样工作的节点集。
<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:exsl='http://exslt.org/common'
xmlns:msxsl='urn:schemas-microsoft-com:xslt'
exclude-result-prefixes='msxsl exsl'>
<xsl:template match='/'>
<!-- result tree fragment -->
<xsl:variable name='_it'>
<em>a</em>
<em>b</em>
<em>c</em>
<em>d</em>
</xsl:variable>
<!-- create a node-set from the result tree fragment -->
<xsl:variable name='it' select='exsl:node-set($_it)'/>
<Root>
<a>
<!--
this is a normal xpath with the variable '$it' and a node 'em'
the number in brackets is the index starting with 1
-->
<xsl:value-of select='$it/em[1]'/> <!-- a -->
<xsl:value-of select='$it/em[2]'/> <!-- b -->
</a>
</Root>
</xsl:template>
<!-- MS doesn't provide exslt -->
<msxsl:script language='JScript' implements-prefix='exsl'>
this['node-set'] = function (x) {
return x;
}
</msxsl:script>
</xsl:stylesheet>