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>
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>
This is a bit hard to find, but it's discussed in Creating Elements with
xsl:element
.While the
{}
syntax is not explicitly discussed here, the meaning of the braces is used similarly in other contexts, such as Creating Elements and Attributes and applies here as well.In this case,
$fieldName
is just an XPath expression for a variable which should evaluate to a valid element name.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.
For example, suppose you have a XML source this one:
and you would like to generate an HTML link from it like
If you simply read the contents of
@site
into thehref
attribute like this:it won't work, since it will be treated as plain text and you will get:
But if you wrap the
@site
in curly braces:It will be treated as XPath, will be executed and you will get:
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: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:These are called
Attribute Value Templates
. See Here for details w3.org