How XSLT Generates JSON, HTML, and Text Output

Extensible Stylesheet Language Transformations (XSLT) is primarily designed to transform XML documents, but modern processors can serialize results into non-XML formats including HTML, plain text, CSV, and JSON. This transformation is achieved by configuring the serialization method via the <xsl:output> element, controlling whitespace handling, and utilizing built-in transformation functions or custom templates designed to construct specific text patterns.

The Role of the <xsl:output> Element

The primary instruction for defining output format in an XSLT stylesheet is the <xsl:output> element. Positioned as a top-level element, it controls the serialization phase of the transformation pipeline.

The method attribute determines how the result tree is converted into the final output stream:

<xsl:output method="html" encoding="UTF-8" indent="yes"/>

Common values for the method attribute include:


Generating HTML Output

When <xsl:output method="html"/> is set, the XSLT processor applies HTML serialization rules rather than standard XML rules.

Key behavioral changes include:


Generating Plain Text and Delimited Files

To create plain text files, CSVs, or custom code files, stylesheets use <xsl:output method="text"/>. In this mode, the processor suppresses all XML element tags in the result tree and writes only text nodes.

Managing Whitespace and Formatting

Because XML structure is stripped away, formatting depends entirely on string construction:

  1. <xsl:text>: Used to explicitly output literal strings, spaces, tabs, and newline characters without interference from XML indentation.
  2. <xsl:strip-space>: Removes unnecessary whitespace nodes from the source XML to prevent unwanted gaps in the output.
  3. Delimiters: Conditional structures like <xsl:if test="position() != last()">,</xsl:if> are used to insert commas or delimiters between records without trailing characters.

Generating JSON Output

JSON generation can be handled via text serialization or native XSLT 3.0 features.

1. Text Serialization (XSLT 1.0 and 2.0)

In older versions of XSLT, JSON is produced by setting method="text" and manually writing the JSON syntax:

2. Native JSON Functions and Methods (XSLT 3.0)

XSLT 3.0 introduced native support for JSON handling through two primary mechanisms:


The Transformation and Serialization Pipeline

An XSLT processor produces non-XML output through a distinct two-step process:

  1. Tree Construction: The processor parses the source XML into an internal tree representation (the XDM data model in XSLT 2.0/3.0) and executes template rules to construct a result tree.
  2. Serialization: The processor reads the result tree and serializes the nodes into a byte stream according to the constraints defined by the chosen <xsl:output> method.