<xsl:element> | |
Allows you to create an element in the output document. It works similarly to the <xsl:attribute> element. | |
Category | |
Instruction |
|
Required Attributes | |
|
|
Optional Attributes | |
|
|
Content | |
An XSLT template. |
|
Appears in | |
<xsl:element> appears inside a template. |
|
Defined in | |
XSLT section 7.1.2, Creating Elements with xsl:element. |
|
Example | |
We'll use a generic stylesheet that copies the input document to the result tree, with one exception: all attributes in the original documents are converted to child elements in the result tree. The name of the new element will be the name of the format attribute, and its text will be the value of the attribute. Because we don't know the name of the attribute until we process the XML source document, we must use the <xsl:element> element to create the result tree. Here's how our stylesheet looks: <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml"/> <xsl:template match="*"> <xsl:element name="{name()}"> <xsl:for-each select="@*"> <xsl:element name="{name()}"> <xsl:value-of select="."/> </xsl:element> </xsl:for-each> <xsl:apply-templates select="*|text()"/> </xsl:element> </xsl:template> </xsl:stylesheet> This stylesheet uses the <xsl:element> element in two places: first to create a new element with the same name as the original element, and second to create a new element with the same name as each attribute. We'll apply the stylesheet to this document: <?xml version="1.0"?> <report> <title>Miles Flown in 2001</title> <month sequence="01"> <miles-flown>12379</miles-flown> <miles-earned>35215</miles-earned> </month> <month sequence="02"> <miles-flown>32857</miles-flown> <miles-earned>92731</miles-earned> </month> <month sequence="03"> <miles-flown>19920</miles-flown> <miles-earned>76725</miles-earned> </month> <month sequence="04"> <miles-flown>18903</miles-flown> <miles-earned>31781</miles-earned> </month> </report> Here are our results: <?xml version="1.0" encoding="UTF-8"?> <report> <title>Miles Flown in 2001</title> <month><sequence>01</sequence> <miles-flown>12379</miles-flown> <miles-earned>35215</miles-earned> </month> <month><sequence>02</sequence> <miles-flown>32857</miles-flown> <miles-earned>92731</miles-earned> </month> <month><sequence>03</sequence> <miles-flown>19920</miles-flown> <miles-earned>76725</miles-earned> </month> <month><sequence>04</sequence> <miles-flown>18903</miles-flown> <miles-earned>31781</miles-earned> </month> </report> The <xsl:element> element created all the elements in the output document, including the <sequence> elements that were created from the sequence attributes in the original document. |