以下示例中的curled bracket {}的含义是什么(在前面的行中,变量$ fieldName被初始化并用字符串填充):
<xsl:element name="{$fieldName}">
<xsl:apply-templates select="field"/>
</xsl:element>
Run Code Online (Sandbox Code Playgroud)
hel*_*cha 33
每当需要在属性中计算表达式时,您可以使用这些花括号(属性值模板),否则这些表达式将内容视为文本.
例如,假设您有一个XML源:
<link site="www.stackoverflow.com"/>
Run Code Online (Sandbox Code Playgroud)
并且你想从它生成一个HTML链接
<a href="http://www.stackoverflow.com">Click here</a>
Run Code Online (Sandbox Code Playgroud)
如果你只是读的内容@site到href这样的属性:
<xsl:template match="link">
<a href="http://@site">Click here</a>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
它将无法工作,因为它将被视为纯文本,您将得到:
<a href="http://@site">Click here</a>
Run Code Online (Sandbox Code Playgroud)
但是如果你@site用花括号包裹:
<xsl:template match="link">
<a href="http://{@site}">Click here</a>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
它将被视为XPath,将被执行,您将获得:
<a href="http://www.stackoverflow.com">Click here</a>
Run Code Online (Sandbox Code Playgroud)
如果它不是花括号,你需要使用<xsl:attribute>in <a>contains <xsl:value-of>来获得相同的结果:
<xsl:template match="link">
<a>
<xsl:attribute name="href">
<xsl:text>http://</xsl:text><xsl:value-of select="@site"/>
</xsl:attribute>
<xsl:text>Link</xsl:text>
</a>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
在您的示例中,nameatrribute <xsl:element>需要一个字符串.要将该字符串视为XPath表达式并将其替换为变量的结果$fieldName,您可以将其放在花括号中,或者使用<xsl:attribute>上面的元素:
<xsl:element>
<xsl:attribute name="name">
<xsl:value-of select="$fieldName"/>
</xsl:attribute>
<xsl:apply-templates select="field"/>
</xsl:element/>
Run Code Online (Sandbox Code Playgroud)
这些被称为Attribute Value Templates.有关详细信息,请参阅此处w3.org
定义:在指定为属性值模板的属性(例如文字结果元素的属性)中,可以通过用大括号({})包围表达式来使用表达式.
属性值模板由固定部分和可变部分的交替序列组成.变量部分由用大括号({})括起来的XPath表达式组成.固定部分可以包含任何字符,但左侧花括号必须写为{{并且右侧花括号必须写为}}.