Home > Articles > Web Services > XML

  • Print
  • + Share This
From the author of

Creating Elements

Adding tags to the page as text is one way to add an element to the final document, but it's not always adequate. In some cases, you have to build an element from scratch. One situation in which this is very common is in the building of a hyptertext link.

Using the methods we've seen so far, we might try to build a link like so:

<xsl:template match="resource">
  <a href="<xsl:value-of select="@location" />">
   <xsl:value-of select="." />
  </a>
</xsl:template>

Unfortunately, this plan has a major flaw: It's not well-formed XML. The culprit is the need to add a value for the attribute. In this situation, we need to use the xsl:element and xsl:attribute elements to build the final structure:

...
<xsl:template match="person"><b><xsl:value-of select="." /></b></xsl:template>

<xsl:template match="resource">
  <xsl:element name="a">
   <xsl:attribute name="href"><xsl:value-of select="@location" /></xsl:attribute>
   <xsl:value-of select="." />
  </xsl:element>
</xsl:template>

<xsl:template match="content/admin">
...

In this example, the xsl:element element creates the <a></a> tag (based on the name="a" attribute). From there, we can add as many attributes as we want with the xsl:attribute element. Note that the @ sign indicates that we're looking for an attribute value, so the following element returns the value of the resource element's location attribute:

<xsl:value-of select="@location" />

We're using this value as the value of an attribute, but it can actually be used anywhere text can be added, just like the value of an element itself.

The content of the xsl:element element determines the actual content of the newly created element, so in this case, an element that starts out as

<resource location="destiny.html">first episode</resource>

ends up as

<a href="destiny.html">first episode</a>
  • + Share This
  • 🔖 Save To Your Account