How to Convert XML to CSV (and When Not To)

How to Convert XML to CSV (and When Not To)

XML does not have rows. That one fact is the whole difficulty of converting it to CSV: a spreadsheet needs a flat list of identically shaped records, and XML gives you a tree with no opinion about which level is the list.

The XML to CSV converter asks you to pick that level, then does the flattening.

Step one: find the record element

Look for the element that repeats once per logical row:

<catalog>
  <book id="bk101">
    <title>XML Developer's Guide</title>
    <author>Gambardella, Matthew</author>
  </book>
  <book id="bk102">…</book>
</catalog>

book is the record; catalog is just the envelope. The converter scans the document, counts how often each element path repeats, and offers them in a dropdown — usually with the right one preselected.

The heuristic prefers containers (elements that have children) over leaves. A <tag> used inside <tags> may repeat more often than <book>, but three tags do not mean three books.

Step two: decide what becomes a column

Once the record is fixed, the mapping is mechanical:

  • Child elements become columns, named by their path — nested <tags><tag> becomes tags/tag.
  • Attributes become @-prefixed columns: id="bk101" becomes @id.
  • Several values in one path — a book with three tags — are joined into one cell with a separator rather than producing three rows.

What gets lost, and why that is fine

CSV has no nesting. Anything you keep from a nested structure is flattened, so round-tripping XML → CSV → XML will not give you back the original document.

That is acceptable when the goal is analysis: pivot tables, sorting, a quick import into a database. It is the wrong tool when the goal is editing the XML.

Common failure modes

Repeating groups inside a record. If a record contains a list, you either join the values into one cell or you get duplicate rows. Both are compromises; joined cells are usually less surprising.

Attributes carrying the identity. If the real data lives in attributes rather than text, remember to include them — that is the “include attributes” checkbox.

Multiple record levels. An invoice with <line-item> children has two possible CSV files: one row per invoice, or one row per line item. If you want to sort or sum by item, choose the deeper element.

If the output looks wrong, the record dropdown is almost always the cause — switch it and watch the columns change.