CSV ↔ XML: Converting Data Between Table and Tree
When to convert between CSV and XML, how to map rows and columns to elements, and how to keep special characters intact.
CSV (Comma-Separated Values) represents data in rows and columns. XML (eXtensible Markup Language) represents hierarchical data with nested elements. Converting between them is common when moving data between spreadsheets, integrations, and APIs.
CSV → XML
The first row is typically treated as headers. Each subsequent row becomes an element with child nodes named after the headers.
name,age
Alice,30
Bob,25<rows>
<row><name>Alice</name><age>30</age></row>
<row><name>Bob</name><age>25</age></row>
</rows>Our CSV → XML tool does this in the browser. It escapes &, <, > and both quote characters in values and wraps the records in <rows> and <row>. It uses your header text as the element names unchanged, so headers must already be valid XML names (see the rules below).
XML → CSV
Choose a consistent row element (e.g., <row>) and use child element names as headers. A value containing a comma, a double quote or a line break must be quoted, with inner quotes doubled, so that a CSV parser reads it back correctly.
<rows>
<row><name>Alice</name><age>30</age></row>
<row><name>Bob</name><age>25</age></row>
</rows>name,age
Alice,30
Bob,25Try XML → CSV. It reads the <row> elements (or the children of the root element if there are none), takes the headers from the child elements of the first row, and ignores attributes.
Character Escaping: The Critical Difference
XML Escaping
XML has five predefined entities. Only < and & must always be escaped in text, but escaping all five is always safe, and that is what most converters do:
| Character | XML Entity | Reason |
|---|---|---|
| < | < | Starts tags |
| > | > | Optional in text. Required only inside the sequence ]]> |
| & | & | Starts entity and character references |
| " | " | Needed inside double-quoted attribute values |
| ' | ' | Needed inside single-quoted attribute values |
CSV Escaping
CSV escaping follows RFC 4180, an informational RFC that describes the common format:
- Fields containing commas, double quotes or line breaks should be enclosed in double quotes (parsers expect it)
- Double quotes within quoted fields must be doubled (
"") - Unquoted fields cannot contain line breaks, and spaces around a field are part of the field
Real-World Use Cases
Legacy System Integration
Many enterprise and partner systems still exchange XML, while spreadsheets and reporting tools want CSV. A conversion step bridges the two without changing either system.
Data Migration
When migrating data between systems with different format requirements, converting with a real parser (rather than string concatenation) keeps the escaping correct.
API Response Transformation
Some APIs return XML while your reporting or analysis needs CSV. Parse the XML, pick the repeating record element, and write one CSV row per record.
Handling Complex Data Structures
Nested XML to Flat CSV
XML supports nested structures, but CSV is flat. When converting nested XML to CSV, you need to decide how to flatten the hierarchy:
- Dot notation:
parent.childbecomes a column name - Bracket notation:
parent[child]becomes a column name - Separate rows: Each nested level becomes a separate row
Arrays in XML
XML arrays can be represented in multiple ways:
<!-- Multiple elements -->
<tags><tag>red</tag><tag>blue</tag></tags>
<!-- Comma-separated -->
<tags>red,blue</tags>
<!-- JSON-like -->
<tags>["red","blue"]</tags>
None of these is more correct than the others, and a generic converter cannot tell which one a document uses. Pick one convention for your data, and write the conversion to match it.
Tips for Reliable Conversion
- Header consistency: Ensure the first CSV row accurately reflects column names. Inconsistent headers cause parsing errors.
- Escaping: XML requires escaping special characters. CSV requires quoting fields containing commas, quotes, or newlines. Always verify escaping is correct.
- Uniform rows: Keep element structures consistent across rows for predictable headers. Mixed structures create ambiguous conversions.
- Validation: Validate XML with a parser. Check CSV with a linter or by importing into a spreadsheet. Invalid XML will cause conversion failures.
- Encoding: Ensure both formats use the same character encoding (UTF-8 recommended). Mismatched encodings cause character corruption.
- Empty values: Decide how to handle empty XML elements - as empty strings, null values, or omitted fields.
Common Conversion Pitfalls
- Lost nesting: Converting deeply nested XML to flat CSV can lose hierarchical relationships
- Array handling: XML arrays may not map cleanly to CSV columns
- Attribute data: XML attributes are often lost when converting to CSV unless explicitly handled
- Namespace issues: XML namespaces can complicate element name mapping
- Large files: Very large XML files may cause memory issues during conversion
A Worked Example: CSV to XML in JavaScript
Converting by hand shows exactly where the rules bite. This script parses with PapaParse, escapes the five predefined entities, and sanitises header names into valid element names. It was run in Node with PapaParse 5:
const esc = (s) => String(s)
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
.replace(/"/g, """).replace(/'/g, "'");
const tag = (h) => {
const t = h.trim().replace(/[^\w.-]+/g, "_");
return /^[A-Za-z_]/.test(t) ? t : "_" + t;
};
const csv = 'first name,2nd,note\nAda,1,"R&D <lead>"\nBob,2,"said ""hi"""';
const { data } = Papa.parse(csv, { header: true });
const rows = data.map((row) =>
" <row>" +
Object.entries(row)
.map(([k, v]) => "<" + tag(k) + ">" + esc(v) + "</" + tag(k) + ">")
.join("") +
"</row>");
console.log("<rows>\n" + rows.join("\n") + "\n</rows>");
// Output:
// <rows>
// <row><first_name>Ada</first_name><_2nd>1</_2nd><note>R&D <lead></note></row>
// <row><first_name>Bob</first_name><_2nd>2</_2nd><note>said "hi"</note></row>
// </rows>Two things happened that a naive converter gets wrong. The header first name contains a space, which is illegal in an XML element name, and 2nd starts with a digit, which is also illegal. Both had to be rewritten. The ampersand and angle brackets in R&D <lead> were escaped. Leave that out and the output is not well-formed XML. The tag helper is a simplification: it replaces anything outside ASCII letters, digits, _, . and -, although XML also allows many non-ASCII letters in names.
XML Names and Characters: The Rules That Break Conversions
- Element names must start with a letter or underscore (a colon is also allowed but is reserved for namespaces in practice), cannot contain spaces, and should not begin with
xmlin any letter case, because the specification reserves those names. CSV headers likeOrder #or2024 totalneed renaming. - Illegal characters: XML 1.0 forbids most control characters (for example U+0001), even when written as a character reference. Text exported from old systems sometimes contains them and must be stripped.
- CDATA sections (
<![CDATA[ ... ]]>) avoid escaping long text, but the sequence]]>cannot appear inside one. Plain escaping is simpler and safer for generated output. - Whitespace: pretty-printed indentation is insignificant in data-oriented XML but is technically text content in mixed-content documents. Do not pretty-print XML whose consumers care about exact text.
Elements or Attributes?
CSV columns can map to child elements or to attributes, and both are valid. Elements are the safer default for generic conversion: they can hold any text, can repeat, and can nest later. Attributes are compact and suit short identifiers, but they cannot contain repeated values, and attribute-value normalisation can alter whitespace.
<!-- Columns as elements -->
<row><id>7</id><name>Ada</name></row>
<!-- Columns as attributes -->
<row id="7" name="Ada"/>Whichever you choose, document it, because the reverse conversion has to make the same decision. A round trip is only reliable when both directions agree on the mapping.
Producing Correct CSV from XML
On the CSV side, the rules are shorter but just as strict. A field containing a comma, a double quote or a line break must be quoted, and quotes inside it are doubled. RFC 4180 also specifies CRLF line endings, although most readers accept a bare LF. Libraries do this correctly. PapaParse's unparse produces:
Papa.unparse([
{ id: 1, note: "a,b", q: 'say "x"' },
{ id: 2, note: "line1\nline2", q: "" },
])
id,note,q
1,"a,b","say ""x"""
2,"line1
line2",Row 2 shows an embedded newline staying inside its quoted field. Hand-built join(",") code loses all of this, which is why CSV exported from XML so often breaks when opened in a spreadsheet.
Flattening Nested XML Reliably
Earlier we listed dot notation as one flattening strategy. Here is a small, tested implementation over already-parsed data. Nested objects get dotted keys and repeated values are joined with a pipe:
const flat = (o, p = "") => Object.entries(o).flatMap(([k, v]) =>
v && typeof v === "object" && !Array.isArray(v)
? flat(v, p + k + ".")
: [[p + k, Array.isArray(v) ? v.join("|") : v]]);
Object.fromEntries(flat({ id: 1, address: { city: "Pune", geo: { lat: 18.5 } }, tags: ["red", "blue"] }))
// { id: 1, 'address.city': 'Pune', 'address.geo.lat': 18.5, tags: 'red|blue' }This yields one stable column set only when every record has the same shape. For irregular data, first take the union of all keys across records, then fill gaps with empty cells, so a missing optional element does not shift the columns. If a record has a repeating child that should become multiple rows (one order with many line items), flatten to one row per child and repeat the parent fields instead of joining.
Security and Scale
- XML External Entities (XXE): when parsing XML you did not create, disable DTD processing and external entity resolution in your parser. Entity expansion attacks such as "billion laughs" exploit parsers that allow nested entity definitions.
- CSV formula injection: cells beginning with
=,+,-or@(OWASP also lists a leading tab or carriage return) can execute in spreadsheet software. When XML from external sources becomes CSV for staff to open in Excel, prefix such cells so they are treated as text. - Memory: a DOM parser holds the whole tree in memory. For very large XML, use a streaming parser and write CSV rows as each record closes. CSV is already row-oriented, so streaming output is straightforward.
- Namespaces: element names such as
ns:itemcarry a namespace URI. Decide whether headers keep the prefix, and remember that prefixes are local aliases, so two documents can bind different prefixes to the same namespace.
Related Reading
If your CSV is headed for a JSON API instead, read the CSV to JSON guide. For a broader view of when each format makes sense, see our guide to data serialization formats. Both directions of the JSON bridge are also covered by the CSV to JSON and JSON to CSV tools.
Use Our Converters
The CSV → XML and XML → CSV converters are deliberately simple:
- CSV → XML parses with PapaParse, treats the first row as headers, and escapes the five predefined entities in values.
- XML → CSV parses with the browser's XML parser, so entities are decoded and malformed XML is rejected, and quotes CSV values only when they need it.
- They do not rename invalid headers, read XML attributes, flatten nested elements or resolve namespaces, so use the techniques above for those cases.
Everything runs in your browser, so the data is not uploaded.
Frequently Asked Questions
How do I convert CSV to XML?
Parse the CSV with a real parser, use the header row as element names, wrap each row in a record element, and escape &, < and > in values. Use the CSV to XML converter to do this without writing code.
Why is my XML invalid after converting from CSV?
The usual causes are unescaped ampersands or angle brackets in values, headers that are not valid element names (spaces, leading digits), and stray control characters. Run the output through an XML parser to get an exact error position.
How do I convert XML with attributes to CSV?
Treat each attribute as its own column, commonly named with a prefix such as @id or row_id so it cannot collide with a child element of the same name. Decide on the convention once and use it for every record. Our XML to CSV tool ignores attributes, so this needs your own code.
Can every XML file be converted to CSV?
Technically any XML can be flattened, but deeply nested or mixed-content documents lose structure in a table. CSV works well when the XML is a list of similar records. For document-like XML, JSON or keeping XML is a better choice.
Written by Kashyap Thakar
Spotted a mistake? Let me know
Try these tools
Use these tools alongside this guide