DEV Community

Alexandre Vazquez
Alexandre Vazquez

Posted on • Originally published at blog.xsltplayground.com

XSLT for beginners: your first transformation

XSLT is a language for transforming XML documents into other formats — another XML structure, HTML, plain text, or JSON. If you are new to it, the learning curve can feel steep because XSLT is declarative and template-driven, which is different from procedural languages. This guide walks you through the core ideas with working examples you can run in XSLT Playground right now.

What XSLT does

You start with an XML source document. You write a stylesheet that describes rules for transforming it. The processor reads both and produces an output document. The stylesheet does not loop through the input line by line — instead, it defines templates that match nodes, and the processor calls those templates as it traverses the document tree.

Your first stylesheet

Start with a simple XML document:




    Design Patterns
    Gang of Four
    45.00


    Clean Code
    Robert Martin
    38.00


Enter fullscreen mode Exit fullscreen mode

Now write a stylesheet that turns this into an HTML table:












            Title
            Author
            Price















Enter fullscreen mode Exit fullscreen mode

Paste both into XSLT Playground and run it. You will see an HTML table with the book data.

Understanding templates

The rule fires when the processor reaches the document root. Inside it, tells the processor to find all book elements inside catalog and call the matching template for each one.

The second template fires once per `book` element. Inside it, extracts the text content of the title child.

This is the core loop of XSLT: match, apply, select.

XPath selects nodes

The select and match attributes use XPath, a path language for navigating XML trees. A few rules you will use constantly:

XPath Meaning
catalog/book book children of catalog
//book All book elements anywhere in the document
book/@id The id attribute of book
book[price > 40] Books whose price exceeds 40
. The current node
.. The parent of the current node

Filtering with predicates

Add a predicate to the apply-templates call to show only books over 40:


Enter fullscreen mode Exit fullscreen mode

Or use xsl:if inside the template:








Enter fullscreen mode Exit fullscreen mode

Sorting output

Use xsl:sort to control the order:




Enter fullscreen mode Exit fullscreen mode

What to try next

Once you are comfortable with templates and XPath:

  • Learn xsl:for-each for inline iteration
  • Explore xsl:choose for multi-branch conditionals
  • Try xsl:variable to store intermediate values
  • Look at xsl:param to pass values into your stylesheet from outside

All of these work in XSLT 1.0, 2.0, and 3.0. The XSLT Playground lets you set the version and experiment without installing anything.

Top comments (0)