XSLT 变量放入花括号 [英] XSLT variable into the curly braces
问题描述
下例中花括号{}是什么意思(在前面几行中,变量 $fieldName 被初始化并用字符串填充):
What is the meaning of curled brackets {} in the following sample (in preceding lines, the variable $fieldName is initialized and populated with string):
<xsl:element name="{$fieldName}">
<xsl:apply-templates select="field"/>
</xsl:element>
推荐答案
当您需要计算属性中的表达式时,您可以使用这些花括号(属性值模板),否则会处理内容作为文本.
You can use these curly braces (attribute value templates) whenever you need to compute an expression in attributes which would otherwise treat the contents as text.
例如,假设您有一个 XML 源:
For example, suppose you have a XML source this one:
<link site="www.stackoverflow.com"/>
并且您想从中生成一个 HTML 链接,例如
and you would like to generate an HTML link from it like
<a href="http://www.stackoverflow.com">Click here</a>
如果你只是像这样将 @site
的内容读入 href
属性:
If you simply read the contents of @site
into the href
attribute like this:
<xsl:template match="link">
<a href="http://@site">Click here</a>
</xsl:template>
它不会工作,因为它将被视为纯文本,您将获得:
it won't work, since it will be treated as plain text and you will get:
<a href="http://@site">Click here</a>
但是如果你把 @site
用大括号括起来:
But if you wrap the @site
in curly braces:
<xsl:template match="link">
<a href="http://{@site}">Click here</a>
</xsl:template>
它将被视为 XPath,将被执行,您将获得:
It will be treated as XPath, will be executed and you will get:
<a href="http://www.stackoverflow.com">Click here</a>
如果不是花括号,您将需要在包含 的
中使用
xsl:value-of> 得到相同的结果:
If it weren't for the curly braces, you would need to use <xsl:attribute>
in <a>
containing an <xsl:value-of>
to obtain the same result:
<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>
在您的示例中,
的 name
属性需要一个字符串.要将字符串视为 XPath 表达式并将其替换为变量 $fieldName
的结果,您可以将它放在花括号中,或者使用 <xsl:attribute>
元素如上:
In your example, the name
atrribute of <xsl:element>
requires a string. To treat that string as an XPath expression and replace it with the result of the variable $fieldName
, you either place it within curly braces as you did, or you use the <xsl:attribute>
element as above:
<xsl:element>
<xsl:attribute name="name">
<xsl:value-of select="$fieldName"/>
</xsl:attribute>
<xsl:apply-templates select="field"/>
</xsl:element/>
这篇关于XSLT 变量放入花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!