How Does XSLT Output Encoding Work?

The encoding attribute in the <xsl:output> element defines the character encoding scheme used by an XSLT processor when serializing the result tree into a byte stream. By specifying an encoding standard such as UTF-8, UTF-16, or ISO-8859-1, you instruct the serializer how to represent characters in the target document, write matching declaration headers, and automatically fall back to numeric character references when a character falls outside the target character set.

Role of the encoding Attribute

In XSLT, transformations occur in an abstract node-tree model where characters exist as independent Unicode code points. Character encoding only becomes relevant during the final serialization step, when the internal result tree is written out as raw text, HTML, or XML bytes.

The <xsl:output> element controls these serialization parameters:

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

When the processor serializes the output, the encoding attribute dictates:

Handling Unrepresentable Characters

Different character encodings support different subsets of the Unicode character repertoire. If a transformation produces a character that does not exist in the designated target encoding, the XSLT serializer handles it based on the output method:

Default Encoding Behaviors

If the encoding attribute is omitted from <xsl:output>, XSLT processors apply default values:

Overriding and Unsupported Encodings

The values supplied to the encoding attribute must match registered charset names recognized by the Internet Assigned Numbers Authority (IANA) or standard Java/C# charset aliases supported by your runtime environment.

If you specify an encoding name that the XSLT processor does not recognize or support, standard XSLT behavior dictates that the processor must either raise an error or fall back to an encoding it does support (typically UTF-8 or UTF-16). When a fallback occurs, the generated output declaration reflects the actual encoding used rather than the unsupported requested value.