XML XSLT Syntax
The XSLT syntax consists of an XML document that defines the transformation rules to be applied to an input XML document.
Syntax
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="version-number" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="output-method" encoding="encoding" omit-xml-declaration="yes|no" />
<xsl:template match="match-pattern">
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h2>Heading</h2>
<xsl:value-of select="expression" />
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="UTF-8" />
<xsl:template match="/">
<html>
<head>
<title>My XML with XSLT Example</title>
</head>
<body>
<h2>Books</h2>
<ul>
<xsl:for-each select="catalog/book">
<li><xsl:value-of select="title" /></li>
</xsl:for-each>
</ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My XML with XSLT Example</title>
</head>
<body>
<h2>Books</h2>
<ul>
<li>Everyday Italian</li>
<li>Harry Potter</li>
<li>Learning XML</li>
</ul>
</body>
</html>
Explanation
The XSLT document contains an xsl:stylesheet element that contains three main parts:
- The xsl:output element specifies the output method and format.
- The xsl:template element specifies a matching pattern and defines the transformation rules for the matched elements.
- The xsl:value-of element is used within the xsl:template element to output the value of a selected element.
The match-pattern
in the xsl:template
element specifies which elements or attributes in the input XML document should be transformed. The select
attribute in the xsl:value-of
element specifies which value should be outputted.
Use
XSLT is mostly used to transform XML data into other formats, such as HTML, XHTML, or even another XML document. XSLT is also used for data extraction, sorting, and filtering.
Important Points
- XSLT is used to transform XML data into other formats.
- An XSLT document contains an xsl:stylesheet element that specifies the transformation rules.
- The xsl:template element defines transformation rules for matched elements.
- The xsl:value-of element is used to output the value of selected elements.
Summary
XSLT is a powerful tool for transforming XML data into other formats. The syntax of XSLT consists of an XML document that defines the transformation rules to be applied to an input XML document. The XSLT document contains an xsl:stylesheet element that specifies the transformation rules. Within the xsl:stylesheet element, xsl:template and xsl:value-of elements are used to define transformation rules for matched elements and output the value of selected elements, respectively.