XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round two / Creating nodes / Creating element nodes with xsl:element

(Excerpt from "XSLT 2.0 & XPath 2.0" by Frank Bongers, Chapter 2.)

The instruction xsl:element adds an element node to the result sequence, as its name suggests. It thus provides, among other things, a somewhat cumbersome-looking alternative to a literal result element:

<element name="beispiel">Test</element>

could be shortened to:

<beispiel>Test</beispiel>

Unlike a literal result element, however, this instruction lets you generate the new element’s name, which must be a QName, using an XPath expression dynamically at runtime.

Put simply, an AVT determines the inserted element’s name only when the element is created. Thus:

<element name="{xpath-ausdruck}">Test</element>

Element names can depend on an element’s position in the sequence being processed. In this somewhat unrealistic example, because HTML has only a few suitable heading tags, appropriately sized headings <h...> are generated in the result document, so there must of course never be more than six books:

<regal>
  <buch>Das erste Buch</buch>
  <buch>Das zweite Buch</buch>
  <!-- mehr Bücher -->
  ...
</regal>

Here is an excerpt from the stylesheet: the attribute-value template appends a digit to »h« according to position:

...
<xsl:template match="buch">
  <xsl:element name="h{fn:position()}">
    <xsl:value-of select="."/>
  </xsl:element>
</xsl:template>
...

In the result document:

<h1>Das erste Buch</h1>
<h2>Das zweite Buch</h2>
... 
<h6>Das sechste Buch</h6>

You can also use this approach to turn attribute names into element names, producing an XML result document. Unlike the previous example, this is a practical application.

The starting point is an empty element <buch> with several attributes:

<buch buchtitel="Wenn der Berg ruft" buchautor="Assmann, Peter" buchverlag="Berg Verlag" ersch-jahr="2004"/>

This is processed as follows; the function fn:name() retrieves the current node’s name each time:

<xsl:template match="buch">
  <buch>
    <xsl:for-each select="@*">
      <xsl:element name="{fn:name()}">
        <xsl:value-of select="."/>
      </xsl:element>
    </xsl:for-each>
  </buch>
</xsl:template>

The result is an element <buch> with no attributes but a series of child elements:

<buch>
  <buchtitel>Wenn der Berg ruft</buchtitel>
  <buchautor>Assmann, Peter</buchautor>
  <buchverlag>Berg Verlag</buchverlag>
  <ersch-jahr>2004</ersch-jahr>
</buch>

Attribute nodes can be created in a similar way.

   

back to top