Generate CSV with XSLT
A practical review of using XSLT to turn XML into CSV or TSV: what the transformation changes, where quoting and encoding go wrong, and when another approach fits better.
XSLT can turn XML into comma-separated or tab-separated text, and it does this reliably when the stylesheet handles delimiters, quoting and line breaks on purpose. XSLT has no built-in CSV serializer. The stylesheet produces plain text, and every rule that makes that text valid CSV has to be written into it. This review covers what the transformation changes, what tends to break, and when a different route makes more sense.
Is XSLT a good fit for producing CSV?
XSLT is a reasonable choice when your data already exists as XML, the structure is mostly flat or predictably repeating, and you want a declarative mapping you can version and rerun. The main benefit is that column selection, ordering and value formatting live in one stylesheet, separate from the code that runs it. That suits pipelines that already use an XSLT processor.
The decisive tradeoff is escaping. You have to implement field quoting yourself. A stylesheet that simply joins values with commas works on clean test data, then produces broken rows the first time a value contains a comma, a double quote or a line break. In XSLT 1.0 this takes noticeably more code than in 2.0 or 3.0.
Another approach is often better in these cases: the export is a one-off, the source is deeply nested with several independent repeating branches, or a general-purpose language with a mature CSV library is already part of your stack. Keeping the data as XML or another structured format is also preferable when downstream users need the hierarchy, attributes or mixed content that a flat table cannot represent.
What the transformation actually changes
XSLT-to-CSV is a structural change to the stored characters. It is not a visual effect. The output is a new text file, and what it contains depends entirely on the stylesheet's mapping. Specifically:
- Hierarchy is flattened: each output row is usually one repeating XML element, and nested children become columns or are dropped.
- Markup disappears: element names, attributes, namespaces and comments are not carried over unless the stylesheet writes them out as values.
- Data types are not recorded: CSV has no notion of numbers, dates or booleans, so every value is text and the consuming application decides how to read it.
- Characters may be rewritten deliberately: quotes are doubled, fields are wrapped in quotes, and line endings are chosen by the stylesheet.
- Silent loss is possible: elements the stylesheet does not select simply do not appear, and nothing in the output signals that they were skipped.
The stylesheet should declare text output so the processor does not add an XML declaration or escape characters as entities. In XSLT this is done with an output instruction using method="text". With XML output, a value such as an ampersand would be written as an entity reference rather than the literal character.
A worked example (XSLT 2.0 or 3.0)
Take this input, which deliberately includes a comma and embedded double quotes:
<orders>
<order>
<id>1001</id>
<customer>Acme, Inc.</customer>
<note>Ships "as is"</note>
</order>
</orders>
The following templates go inside a stylesheet that declares the standard XSLT namespace and version 2.0 or later. A field is quoted only when it contains a comma, a double quote or a line break, and any embedded double quote is doubled. This is the convention described in RFC 4180, the most widely cited CSV description.
<xsl:output method="text" encoding="UTF-8"/>
<xsl:template match="/orders">
<xsl:text>id,customer,note </xsl:text>
<xsl:for-each select="order">
<xsl:value-of select="string-join(
for $v in (string(id), string(customer), string(note)) return
if (matches($v, '[," ]'))
then concat('"', replace($v, '"', '""'), '"')
else $v,
',')"/>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
Following the rules in that stylesheet, the input above maps to:
id,customer,note
1001,"Acme, Inc.","Ships ""as is"""
Two details in the example matter. First, each column is wrapped in string(), so a missing element yields an empty field instead of vanishing from the sequence. Without that, a missing element would shift every later column one position left. Second, carriage return and line feed appear as character references. A literal line break typed inside an attribute value is normalized to a space by the XML parser, so the regular expression would no longer detect it.
The XSLT 1.0 version is more work
XSLT 1.0 has no replace(), matches() or string-join(). Doubling quotes requires a recursive named template, and the check for whether to quote a field has to be built from contains() tests. This matters because the XSLT processors built into web browsers have generally been limited to 1.0. Check which version your processor supports before choosing an approach.
<xsl:template name="escape-quotes">
<xsl:param name="s"/>
<xsl:choose>
<xsl:when test="contains($s, '"')">
<xsl:value-of select="concat(substring-before($s, '"'), '""')"/>
<xsl:call-template name="escape-quotes">
<xsl:with-param name="s" select="substring-after($s, '"')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$s"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
Switching to TSV
Changing the separator to a tab (written as in the stylesheet) produces tab-separated output. TSV is usually handled without a quoting convention, so a value that contains a tab or a line break cannot be represented safely. You need to decide whether to replace such characters, for example with a space, or to stop the transformation with an error. Quietly passing them through produces rows that split in the wrong places.
Will the output stay usable after you share it?
Because the result is plain text, it copies, pastes, searches and diffs like any other text file. Most usability problems appear when another program interprets the file. The table below lists the common risk points and what the stylesheet can do about each.
| Issue | What can go wrong | What the stylesheet can control |
| Encoding | Non-ASCII characters display incorrectly if the consumer assumes a different encoding | Declare the output encoding; in XSLT 2.0 and later, the byte-order-mark serialization option can add a UTF-8 BOM, which some consumers rely on to detect encoding |
| Line endings | Some tools expect CRLF, others LF | Emit the line ending you have chosen explicitly instead of relying on line breaks inside the stylesheet |
| Delimiter | Spreadsheet settings in some locales expect a semicolon rather than a comma | Make the delimiter a parameter so it can be changed without editing the logic |
| Type guessing | Spreadsheets may strip leading zeros, reformat long numbers or reinterpret date-like text | Little; CSV cannot mark a value as text, so document this for recipients or supply an import specification |
| Formula-like values | Fields beginning with =, +, - or @ may be treated as formulas when opened in a spreadsheet (often called CSV or formula injection) | Detect such leading characters in untrusted values and neutralize them according to your recipients' requirements |
| Missing or repeated elements | Columns shift, or an XSLT 2.0+ processor raises a type error when string() receives more than one node | Map columns explicitly and decide whether repeats should be joined, take the first value, or fail |
In accessibility terms, a CSV file has no reading-order or presentation layer of its own. It is read row by row, left to right, so the experience with assistive technology depends on the application that opens it. A header row with clear column names is the main thing the stylesheet contributes. No tested results for specific screen readers or spreadsheet applications were available for this review, so check with the tools your recipients actually use.
Keep the source XML, or provide a plain-text or structured equivalent, whenever the flattened table cannot carry the full meaning. Examples include records with variable-length nested lists, values that depend on attributes the CSV omits, or long prose fields where embedded line breaks make the CSV hard to read in a basic text editor.
Gaps in this review
This assessment rests on the documented behavior of XSLT and on common CSV conventions. It contains no measurements, performance figures or test runs against named XSLT processors, spreadsheet programs or assistive technologies. Behavior around BOM handling, delimiter detection and type conversion differs between consuming applications. Confirm it with a small sample file containing commas, quotes, line breaks, non-ASCII characters and leading zeros before relying on the export in production.