Xslt Examples in XML
Sure! Here are several XSLT examples in XML, demonstrating common use cases:
1?? Simple Copy of XML (Identity Transform)
Copies the input XML exactly as output.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template></xsl:stylesheet>2?? Transform XML to HTML List
Input XML:
<fruits> <fruit>Apple</fruit> <fruit>Banana</fruit> <fruit>Cherry</fruit></fruits>XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/fruits"> <html> <body> <h2>Fruit List</h2> <ul> <xsl:for-each select="fruit"> <li><xsl:value-of select="."/></li> </xsl:for-each> </ul> </body> </html> </xsl:template></xsl:stylesheet>3?? Conditional Processing with <xsl:choose>
Transform people based on age.
Input XML:
<person> <name>Jane</name> <age>30</age></person>XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="person"> <div> <p>Name: <xsl:value-of select="name"/></p> <p>Status: <xsl:choose> <xsl:when test="age < 18">Minor</xsl:when> <xsl:when test="age >= 18 and age < 65">Adult</xsl:when> <xsl:otherwise>Senior</xsl:otherwise> </xsl:choose> </p> </div> </xsl:template></xsl:stylesheet>4?? Modify XML Data (Increase Price)
Input XML:
<product> <name>Gadget</name> <price>100</price></product>XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <!-- Identity template copies everything --> <xsl:template match="@*|node()"> <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy> </xsl:template> <!-- Increase price by 20 --> <xsl:template match="price"> <price><xsl:value-of select=". + 20"/></price> </xsl:template></xsl:stylesheet>If you want, I can generate full working XML + XSLT pairs and explain how to run these transformations in browsers or tools!