To transform XML to another XML/HTML/TEXT format using XSLT., we need the following files.
- Input XML (.xml)
- XSLT file which contains the transformation script. (.xsl)
The below XML (input.xml) input file, can be transformed into a html with the xsl (trans.xsl) file.
Sample Input XML:
File: input.xml
1 2 3 4 5 6 7 8 9 |
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet href="trans.xsl" type="text/xsl" ?> <Person> <Name>Sherlock</Name> <Profession>Detective</Profession> <Country>England</Country> </Person> |
In the above XML file, we could see xml-stylesheet tag which defines the transformation xsl file., which when opened by Chrome/Firefox browser,
The transformation will be applied and output will be displayed in the browsers.
Tranformation XSL:
File: trans.xsl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes" /> <xsl:template match="/"> <html> <table border="1"> <tr> <td colspan="2" style="font-weight:bold;font-size: 1.6em; ">Details </td> </tr> <tr> <td style="font-weight:bold;">Name</td> <td> <xsl:value-of select="Person/Name" /> </td> </tr> <tr> <td style="font-weight:bold; ">Profession</td> <td> <xsl:value-of select="Person/Profession" /> </td> </tr> <tr> <td style="font-weight:bold; ">Country</td> <td> <xsl:value-of select="Person/Country" /> </td> </tr> </table> </html> </xsl:template> </xsl:stylesheet> |
- The xsl:stylesheet with xmlns:xsl attribute defines the file is a XSL tranformation content.,
- The <xsl:value-of> tag defines the value present in the source xml content values.
- The “select” attribute defines the corresponding XPATH in the source xml(input.xml)
- e.g., Person/Name defines the value of input XML tag elements value “Sherlock” ( Traverse through the XPATH Sherlock )
Finally, Once done, when Opening the input.XML file in the browser, the corresponding transformation is applied and the output will be like below.
Details | |
Name | Sherlock |
Profession | Detective |
Country | England |
The output source code after the transformation is below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<html> <table border="1"> <tr> <td colspan="2" style="font-weight:bold;font-size: 1.6em; ">Details </td> </tr> <tr> <td style="font-weight:bold;">Name</td> <td>Sherlock</td> </tr> <tr> <td style="font-weight:bold; ">Profession</td> <td>Detective</td> </tr> <tr> <td style="font-weight:bold; ">Country</td> <td>England</td> </tr> </table> </html> |