XSLT:在 XSLT 中创建地图 [英] XSLT : Creating a Map in XSLT
问题描述
我想在 xsl 中有一个键值映射,因此定义了一个具有 xml 片段的变量,但是稍后当我尝试访问变量中的 xml 节点时,我收到一个错误,即无法解析 xpath xpression 的类型.
I want to have a key value map in xsl and so defined a variable which has an xml fragment, but later when I try to access the xml nodes in the variable I get an error that type of the xpath xpression cannot be resolved.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:variable name="map">
<map>
<entry key="key-1">value1</entry>
<entry key="key-2">value2</entry>
<entry key="key-3">value3</entry>
</map>
</xsl:variable>
<output>
<xsl:value-of select="$map/entry[@key='key-1']"/>
</output>
</xsl:template>
</xsl:stylesheet>
推荐答案
XSLT 2.0
使用 XSLT 2.0,以下解决方案有效:
XSLT 2.0
Using XSLT 2.0, the following solution works:
<xsl:variable name="map">
<entry key="key-1">value1</entry>
<entry key="key-2">value2</entry>
<entry key="key-3">value3</entry>
</xsl:variable>
<xsl:template match="/">
<output>
<xsl:value-of select="$map/entry[@key='key-1']"/>
</output>
</xsl:template>
XSLT 1.0
您不能在 XSLT 1.0 的 XPath 表达式中使用结果树片段,但 fn:document()
可以检索地图值.类似的问题 将在这里工作:.
XSLT 1.0
You cannot use a result tree fragment in a XPath expression in XSLT 1.0, but fn:document()
can retrieve map values. An answer to a similar question will work here:.
<xsl:value-of select="document('')//xsl:variable[@name='map']/map/entry[@key='key-1']"/>
如XSLT 1.0 规范中所述:
document('')
指的是样式表;那个树样式表的表示是与 XML 完全相同包含样式表的文档是初始源文件.
document('')
refers to the root node of the stylesheet; the tree representation of the stylesheet is exactly the same as if the XML document containing the stylesheet was the initial source document.
但是,您不需要为此使用 xsl:variable
.你可以直接在 xsl:stylesheet
下指定你的地图节点,但你必须记住顶级元素必须有一个非空的命名空间 URI:
However, you don't need to use xsl:variable
for this. You could specify your map node directly under xsl:stylesheet
, but you must remember that a top level elements must have a non null namespace URI:
<xsl:stylesheet
version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="some.uri" exclude-result-prefixes="my">
<my:map>
<entry key="key-1">value1</entry>
<entry key="key-2">value2</entry>
<entry key="key-3">value3</entry>
</my:map>
<xsl:template match="/">
<output>
<xsl:value-of select="document('')/*/my:map/entry[@key='key-1']"/>
</output>
</xsl:template>
</xsl:stylesheet>
这篇关于XSLT:在 XSLT 中创建地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!