7.2 Stylesheet and transformation – XSLT
Definition
XSLT (eXtensible Stylesheet Language Transformations) is the recommended style sheet language for XML.
XSLT is far more sophisticated than CSS. With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange and sort elements, perform tests and make decisions about which elements to hide and display, and a lot more.
XSLT uses XPath to find information in an XML document.
How XSLT Works
An XSLT stylesheet is used to define the transformation rules to be applied on the target XML document. XSLT stylesheet is written in XML format. XSLT Processor takes the XSLT stylesheet and applies the transformation rules on the target XML document and then it generates a formatted document in the form of XML, HTML, or text format. This formatted document is then utilized by XSLT formatter to generate the actual output which is to be displayed to the end-user.
Advantages
Here are the advantages of using XSLT −
∙ Independent of programming. Transformations are written in a separate xsl file which is again an XML document.
∙ Output can be altered by simply modifying the transformations in xsl file. No need to change any code. So Web designers can edit the stylesheet and can see the change in the output quickly.
XSLT Example
We will use the following XML document:
Example 1
1. <?xml version="1.0" encoding="UTF-8"?> 2. <breakfast_menu> 3. 4. <food> 5. <name>Belgian Waffles</name> 6. <price>$5.95</price> 7. <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description> 8. <calories>650</calories> 9. </food> 10. 11. <food> |
12. <name>Strawberry Belgian Waffles</name> 13. <price>$7.95</price> 14. <description>Light Belgian waffles covered with strawberries and whipped cream</description> 15. <calories>900</calories> 16. </food> 17. 18. <food> 19. <name>Berry-Berry Belgian Waffles</name> 20. <price>$8.95</price> 21. <description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> 22. <calories>900</calories> 23. </food> 24. 25. <food> 26. <name>French Toast</name> 27. <price>$4.50</price> 28. <description>Thick slices made from our homemade sourdough bread</description> 29. <calories>600</calories> 30. </food> 31. 32. <food> 33. <name>Homestyle Breakfast</name> 34. <price>$6.95</price> 35. <description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> 36. <calories>950</calories> 37. </food> 38. 39. </breakfast_menu> |
Example 2
1. <?xml version="1.0" ?> 2. <persons> 3. <person username="JS1"> 4. <name>John</name> 5. <family-name>Smith</family-name> 6. </person> 7. <person username="MI1"> 8. <name>Morka</name> 9. <family-name>Ismincius</family-name> 10. </person> 11. </persons> |