I have started using XSLT just recently and am wondering what the effective difference is between using <xsl:element> for defining elements vs. just declaring them as literals in the XSLT. For example, lets take a simplified case where I’m converting the contents of a tiny XML document into (x)HTML.
1.I could go with the <xsl:element> way:
<xsl:element name="h1">
<xsl:value-of select="heading"/>
</xsl:element>
2. Or define the element by hand:
<h1>
<xsl:value-of select="heading"/>
</h1>
What is the actual difference between these two and if a difference exists, which of them is considered ‘good-style’?
They’re almost identical, the exception being that a literal
<h1>element will add to the result tree the namespace nodes that are in scope at that point in the stylesheet, whereas the<xsl:element name="h1">won’t. What difference this makes to your output depends on exactly what namespace declarations your stylesheet includes and where in the result tree you make use of them, if at all. For example, run against any input XML document the following transform:produces the following output (using xsltproc):
but changing the literal
<root>in the stylesheet to<xsl:element name="root">instead producesas the
<xsl:element>form doesn’t attach the “foo” namespace node to the generated element. If this matters, and you actually want to copy the stylesheet namespace declarations onto an element you create with<xsl:element>you can do so by nesting something likedirectly inside it (using the idiom of
document('')which provides access to the stylesheet XML document itself).But generally, the main use of
<xsl:element>is when the element name is calculated rather than a “compile-time” literal.