Your First Step To Write XSLT
Tags: xslt, xml, html, css
Published: 2022-05-15 06:36:55


## Introduction about XSLT 📖
The XSLT is the abbreviation of eXtensible Stylesheet Language Transformation
xslt is a language of transforming XML documents so we can consider it as a style sheet for XML like CSS is a style sheet for HTML, also the XSLT files extensions end with .xslt or .xsl each of them is a valid extension.

## Why to use XSLT 🤔
we can transform XML file to another XML file after making some modifications, also we have the ability to convert XML file to HTML page, like this example we have some products in a category and we need to create a table with these products.

```
<?xml version="1.0" encoding="UTF-8"?>
<category>
<product>
     <name>watch</name>
     <price>50.60$</price>
</product>
<product>
      <name>IPhone 13</name>
      <price>5055.999$</price>
</product>
<product>
      <name>wallet</name>
      <price>5.10$</price>
</product>
</category>
``` 


![product - category](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnmoblv28zyzkcrm39th.png)

### that was done just with XSLT code, so lets go a little bit deep in XSLT 👨‍💻

## XSLT Basic Architecture 🧱
### Elements
We have some element that we can use in xslt language you can find most of them in the [reference](https://www.w3schools.com/xml/xsl_elementref.asp)

> **for-each and value-of**  are called elements, so as a conclusion every param after **xsl:** is called element

```
<xsl:for-each select="expression">
  <!-- Content -->
</xsl:for-each>
<xsl:value-of select="expression" disable-output-escaping="yes|no" />
``` 
and by the way any word written beside the element within its scope in <> signs is called attribute so if i need to add id for each product i can put id attribute in each product element like that.

```
<product id=1>
     <name>watch</name>
     <price>50.60$</price>
</product>
```
but how to use these elements and how to tell the editor to include these elements and recognize them, all of these questions's answer is namespace of this language.

### Namespace
The first thing you should write in xslt file is the namespace and you can write it with two different ways but with the same result at the end.

Also it is like adding the import package line in java.

```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
``` 

```
<xsl:transform version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
``` 
> **xsl:stylesheet** and **xsl:transform** are completely identical in the functions 


### Variables 
we can declare as usual in programming languages global or local variable but the difference here is once you set the variable's value you can't modify or change that value so it is consider as final in language like Java, PHP and Dart, let's go forward to see how to declare a variable 
```
<xsl:variable name="name" select="expression"> </xsl:variable>
``` 
```
<xsl:variable name="color" select="'red'" />
``` 
the name of variable can be set in the name attribute also the value of the variable can be set in select attribute but we have one constrain here that we should put variable's value if it will be a string in quotes like red in the example not just put the value.
 

Also we can put the value from xml’s element to variable by adding its path in select attribute, like if we need to put price of the product in a variable.

``` 
<xsl:variable name="price" select="category/product/price/text()" />
``` 
text() just to convert value to string like previous example.

### Loops
Its very easy in other language to write a for loop just write for with specific condition also here its a quite similar but with different keyword <xsl:for-each> so it will be like that.

```
<xsl:for-each select="expression">
  <!-- Content -->
</xsl:for-each>
```
We will put in the select attribute the path of element that we need to loop in like in our category - product example we should put the path of products like that 

```
<xsl:for-each select="category/product">.
  <!-- Content -->
</xsl:for-each>

```
so now in this point we are ready to loop over all products with the final step to get the name of the product and the price to put them into table, but how about if we need to just show the product with specific price by checking the price if it is higher than or less than or equal to an arbitrary value? of-course as you thought, so lets go and eat a very delicious meal conditions 😅.

### Conditions 
We have two ways to make a conditions the first one like usual if.
```
<xsl:if test="expression">
  ...some output if the expression is true...
</xsl:if>
```
as we know now test is attribute, we should put our condition instead of expression in the test attribute,
**but** as not usual we have constant symbols for comparing 

```
- &gt;  -> means greater than
- &lt;  -> means less than
-  =    -> means equal
- !=    -> means not equal
```

like if we need products which prices are greater than 10$, so stuff like that can be done by using loops and conditions together as shown.

```
<xsl:for-each select="category/product">
      <xsl:if test="price &gt; 10">
             <!-- Content -->
      </xsl:if>
    </xsl:for-each>
```

the second way is like switch case in other languages in xslt called choose - when.
```
<xsl:choose>
  <xsl:when test="expression">
             <!-- Content 1-->
  </xsl:when>
  <xsl:otherwise>
             <!-- Content 2 -->
  </xsl:otherwise>
</xsl:choose>
```
also we can add when statements as we need, now lets implement the condition of products but with choose - when.

```
<xsl:for-each select="category/product">
      <xsl:choose>
        <xsl:when test="price &gt; 10">
                      <!-- display product -->
        </xsl:when>
        <xsl:otherwise>
                      <!-- hide product -->
        </xsl:otherwise>
      </xsl:choose>
 </xsl:for-each>
```
but what can we do if we will write the same code in different places to make some logic but in a typical way, yes you are right use functions, lets do it 💪

### Functions
In c++ to write function you need to write its name and parameters also its return value type, here we just need name and parameter so you can return any type you need.

```
 <xsl:function name="functionName">
    <xsl:param name="param1"/>
    <xsl:param name="param2"/>
    <xsl:value-of select="return value"/>
  </xsl:function>
```

so it is very easy to declare a function also it is very easy to call it like that.

```
<xsl:value-of select="functionName('param1','param2')"/>
```

can you tell me what does this function do?
```
 <xsl:function name="arbitraryName">
    <xsl:param name="param1"/>
    <xsl:param name="param2"/>
    <xsl:value-of select="$param1 + param2"/>
  </xsl:function>

<xsl:value-of select="arbitraryName('param1','param2')"/>
```

yes you are right just add 2 numbers.
Great let me tell you congratulations 🎉 you are now ready to see how could we write the file that convert xml to html tables.

but one step before, do you remember "<!--Content --" that we always wrote in if's body also in for's body? ok great, we could replace this comment with what we want like html tags if we need to convert xml file to html or xml elements whatever want, do you imagine what you will see now in the code? yes exactly just i will add some html tags that construct the tables and put some CSS styling in the tag so it will be easy peasy dude 😃.

```
<!-- namespace and version -->
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">


<!-- access the root element  -->
<xsl:template match="/">
  <html>
    <body>
      <h2 align="center">My Products Collection</h2>
        <table border="1" align="center">
          <tr bgcolor="#9acd32">
             <th>Name</th>
             <th>Price</th>
          </tr>

<!-- access the path to products  -->
       <xsl:for-each select="category/product">
       
<!-- display all product without any conditions  -->
       <tr>
         <td><xsl:value-of select="name"/></td>
         <td><xsl:value-of select="price"/></td>
       </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>

</xsl:stylesheet>
```

![product - category](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnmoblv28zyzkcrm39th.png )

## Conclusion 😃
What we did with Xslt we can also did with any programming language but in some cases choice of xslt is more powerful and optimized than coding with your language.