Convert XML to CSV with XSLT

How an XSLT stylesheet turns XML into CSV, what it keeps and loses, how to quote fields correctly, and when the CSV holds up after it is shared.

XSLT can turn XML into CSV by having the stylesheet write plain text instead of markup. Whether the result is usable depends less on stylesheet syntax than on whether the XML fits into rows and columns. This review covers what the conversion changes, where meaning can be lost, and how the CSV behaves once it leaves the processor.

Short verdict

XSLT is a good fit when the XML is record-oriented, meaning a repeating element where each record has a predictable set of single-valued children or attributes. The main benefit is a declarative, repeatable mapping. You can keep the stylesheet under version control next to the data, run it with any conforming processor, and see every column choice written out explicitly.

The decisive tradeoff is that CSV is flat. Anything hierarchical has to be flattened, joined or dropped, and the stylesheet hard-codes those decisions. That includes nested lists, repeated child elements, mixed text and markup, namespaces, and the difference between attributes and elements.

Keep the XML, or another format that preserves structure, in three cases: when the hierarchy carries meaning, when the content is document-like prose, or when the CSV would need so many joined or duplicated values that readers could no longer reconstruct the original records.

What the transformation actually changes

This conversion changes stored characters and structure. It is not a visual effect. Text-styling tools that reverse words, mirror glyphs, substitute Unicode lookalike "fonts" or apply CSS presentation change how text appears. An XSLT processor does something different: it reads an XML tree and writes a new text file.
The words "reverse", "mirror" and "font" as those tools use them do not apply here. Bidirectional display matters only if field values contain right-to-left scripts. Even then, the CSV stores the same characters in the same logical order as the source.

Three things happen during the conversion:
1) Selection. XPath expressions choose which nodes become rows and which values become columns.
2) Serialization. With xsl:output method="text", the processor emits string values without tags and without escaping XML special characters.
3) Delimiting and quoting. XSLT does not do this for you. The text output method has no concept of CSV, so the stylesheet itself must handle commas, quotation marks and line breaks inside values.

A worked example

The input below has two records. One value contains a comma, one contains quotation marks, and one record has an empty element.

<orders>
  <order id="101">
    <customer>Ada Lovelace</customer>
    <item>Notebook, lined</item>
    <note>Ships "as is"</note>
  </order>
  <order id="102">
    <customer>Grace Hopper</customer>
    <item>Pens</item>
    <note/>
  </order>
</orders>

The templates below require XSLT 2.0 or later because they use replace() and the separator attribute on xsl:value-of. Place them inside an xsl:stylesheet element that declares the standard XSLT namespace and sets version to 2.0 or higher.

<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/">
  <xsl:text>id,customer,item,note&#10;</xsl:text>
  <xsl:apply-templates select="orders/order"/>
</xsl:template>

<xsl:template match="order">
  <xsl:value-of separator=","
      select="for $v in (string(@id), string(customer), string(item), string(note))
              return concat('&quot;', replace($v, '&quot;', '&quot;&quot;'), '&quot;')"/>
  <xsl:text>&#10;</xsl:text>
</xsl:template>

The stylesheet produces this output:

id,customer,item,note
"101","Ada Lovelace","Notebook, lined","Ships ""as is"""
"102","Grace Hopper","Pens",""

The output can be checked against the mechanism:
• Every value is wrapped in double quotes, and any internal quote is doubled. This is the convention described in RFC 4180 for CSV. It is why Notebook, lined stays a single field and why Ships "as is" becomes "Ships ""as is""".
• Each value is passed through string(), so a missing element produces an empty field. Without string(), a record with no note element would silently produce three fields instead of four, and the columns would no longer line up with the header.
• The sample values contain no combining marks or multi-code-point emoji. Because the conversion copies characters unchanged rather than reordering them, such sequences would pass through intact, provided the input and output encodings are handled correctly.

Many installed processors support only XSLT 1.0, including those built into common libraries and web browsers. XSLT 1.0 has no replace() function and no separator attribute. Doubling quotes therefore needs a recursive named template, and you have to write delimiters between fields by hand. Expect a noticeably longer stylesheet. To check which version your processor supports, evaluate system-property('xsl:version') before choosing an approach.

Where meaning can be lost

Source XML feature | What happens in CSV | Typical handling
Repeated child elements, such as several phone numbers | No single cell holds them naturally. With the example stylesheet, a second customer element causes a processing error rather than silent loss | Join the values with a secondary delimiter, pick one value, or emit one row per child and repeat the parent's values
Nested records | The hierarchy is flattened | Produce a separate CSV for each level linked by key columns, or denormalize into one table
Attributes vs. elements | The distinction disappears | Record the mapping in the column names or in accompanying documentation
Mixed content (text with inline markup) | Markup is dropped and text fragments are run together | Usually a sign that CSV is the wrong target
Namespaces | Prefixes are not carried into the CSV, and unprefixed XPath paths match nothing unless the namespace is declared in the stylesheet | Declare the namespace prefixes in the stylesheet and use them in XPath
Empty vs. missing elements | Both become empty fields | Add a flag column if the difference matters
Numbers and dates | Copied exactly as written in the source | Normalize them in the stylesheet if the destination expects a particular format

Readability and usability after copying or sharing

The output is ordinary text, so copying and pasting preserves the exact characters. Unlike styled Unicode text, there are no lookalike glyphs for search to miss or for screen readers to announce strangely. Reading order is the order of the output: the header row first, then records in document order unless the stylesheet sorts them with xsl:sort. The practical limits come from how each destination interprets the text.

  • Encoding: Declare the encoding on xsl:output and confirm the destination reads it the same way. Some spreadsheet software may assume a different encoding for CSV files that lack a byte order mark, which garbles non-ASCII characters. Test with real data.
  • Line endings: The example writes LF (
  • ), while RFC 4180 specifies CRLF. Many tools accept either. If a consumer is strict, emit
  • instead.
  • Delimiter and locale: Where the comma is the decimal separator, spreadsheet applications may expect semicolons between fields. Comma-delimited files are the usual default for US readers.
  • Type conversion: Spreadsheet applications can change values when they open a file. They may drop leading zeros from IDs or read code-like strings as dates. Quoting the values in the file does not reliably prevent this. Importing those columns as text does.
  • Formula injection: A value beginning with =, +, - or @ may be treated as a formula when the file is opened in a spreadsheet. If the XML comes from untrusted sources, neutralize these values in the stylesheet or during import.
  • Line breaks inside values: A quoted value may legally contain line breaks. Line-oriented tools such as grep or simple scripts will still see that record split across several lines.

CSV has no captions and no structural markup, so the header row is the only description of the columns. Use clear column names, and include units in them where relevant. When the file is opened in a spreadsheet, access through assistive technology depends on that application, not on the conversion. This review did not test any specific screen reader or application, so check the actual destination before relying on it. If readers need context that the CSV cannot hold, such as hierarchy, units or notes, provide a plain-text description alongside the file or point readers to the source XML.

How to check a conversion before relying on it

  • Compare the number of source records, for example count(/orders/order), with the number of data rows in the CSV.
  • Parse the output with a CSV-aware parser rather than splitting lines on commas, and confirm that every row has the same number of fields as the header.
  • Run test data that includes awkward values: commas, quotation marks, line breaks, leading zeros, non-ASCII text, empty elements and missing elements.
  • Open the file in the actual destination application or import pipeline, and inspect the columns that are prone to type conversion.
  • Keep the XML as the source of record whenever the flattening choices discard information someone may need later.

Evidence and gaps

This review is based on the documented behavior of XSLT and XPath and on the CSV conventions in RFC 4180. It does not report tests of specific processors, performance figures, or results from particular spreadsheet applications or assistive technologies. Statements about destinations are general cautions to verify in your own environment, not observed results.