我在 XSLT 中创建了一个变量,并且尝试从该变量内的元素读取值。尝试调试时,我在 Visual Studio 中收到以下错误消息:
"To use a result tree fragment in a path expression, first convert it to a node-set using the mxsxl:node-set() function".
据我了解,mssxl
不是“真正的”xslt 函数,并且它可能无法在某些系统上运行;所以我不想使用它。
如何从 XSLT 变量中的特定元素获取值?
这是我的代码。
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:variable name ="TestVariable">
<video id ="0">foo1</video>
<video id ="2">foo2</video>
<video id ="3">foo3</video>
<video id ="4">foo4</video>
<video id ="5">foo5</video>
<video id ="6">foo6</video>
</xsl:variable>
<xsl:template match="/">
<outofloop>
<a2>
<xsl:value-of select="$TestVariable/video[@id='6']" />
</a2>
</outofloop>
</xsl:template>
</xsl:stylesheet>
最佳答案
您拥有的 XSLT 将在 XSLT 2.0 中运行。
问题在于,在 XSLT 1.0 中,您的 TestVariable 变量保存所谓的“结果树片段”,因此 XSLT 无法访问它,因为它确实需要节点集。您可以通过扩展函数将其转换为节点集。事实上,该函数被命名为 node-set 很有帮助。 .
所以,你可以这样做
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ms="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="ms">
<xsl:variable name ="TestVariable">
<video id ="0">foo1</video>
<video id ="2">foo2</video>
<video id ="3">foo3</video>
<video id ="4">foo4</video>
<video id ="5">foo5</video>
<video id ="6">foo6</video>
</xsl:variable>
<xsl:template match="/">
<outofloop>
<a2>
<xsl:value-of select="ms:node-set($TestVariable)/video[@id='6']" />
</a2>
</outofloop>
</xsl:template>
</xsl:stylesheet>
但正如您所指出的,这会限制其可移植性。
还有另一种方法,那就是使用 document 函数来允许 XSLT 将自身引用为输入文档。像这样简单地定义一个变量
<xsl:variable name="Test" select="document('')//xsl:variable[@name='TestVariable']" />
然后你就可以这样做
<xsl:value-of select="$Test/video[@id='6']" />
因为Test引用一个输入文档,所以它现在直接保存一个节点集,因此不需要扩展函数。
也试试这个 XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name ="TestVariable">
<video id ="0">foo1</video>
<video id ="2">foo2</video>
<video id ="3">foo3</video>
<video id ="4">foo4</video>
<video id ="5">foo5</video>
<video id ="6">foo6</video>
</xsl:variable>
<xsl:variable name="Test" select="document('')//xsl:variable[@name='TestVariable']" />
<xsl:template match="/">
<outofloop>
<a2>
<xsl:value-of select="$Test/video[@id='6']" />
</a2>
</outofloop>
</xsl:template>
</xsl:stylesheet>
关于xml - XSLT:如何从变量中的某个元素获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21321056/