Guide

How to Convert CSV to XML: Element Names, Escaping, and Valid Output

Turn CSV rows into well-formed XML. Learn how to name elements, escape special characters, handle empty values, and check the result before you import it.

XML has a reputation for being old, and fair enough. But it hasn’t gone anywhere. Accounting packages, government portals, product feeds, ERP imports and a lot of enterprise software still want it. So sooner or later somebody hands you a spreadsheet export and says the upload form only takes .xml.

The conversion looks trivial. A row is a record, a column is a field, done. Then the upload fails with an error about line 4,812, and it turns out one company name had an ampersand in it.

This guide covers how a CSV maps onto XML, the three things that actually break conversions (bad element names, unescaped characters and invalid control characters), the decisions about elements, attributes and empty values, and ways to do the conversion and check the output.

How rows and columns become XML

Think of XML as nested labelled boxes. A CSV file maps onto it naturally:

  • The whole file becomes one root element, like <orders>.
  • Each row becomes a repeating record element, like <order>.
  • Each column becomes a child element inside the record, named after the header.
  • Each cell value becomes the text inside that child element.

So this CSV:

order_id,customer,total
1001,Ana Rao,49.50
1002,Raj Mehta,12.00

becomes this XML:

<?xml version="1.0" encoding="UTF-8"?>
<orders>
  <order>
    <order_id>1001</order_id>
    <customer>Ana Rao</customer>
    <total>49.50</total>
  </order>
  <order>
    <order_id>1002</order_id>
    <customer>Raj Mehta</customer>
    <total>12.00</total>
  </order>
</orders>

The first line is the XML declaration, which also states the encoding. XML requires exactly one root element, which is why you can’t just list the records one after another. The names orders and order aren’t in your CSV, so you have to choose them, and sometimes the system receiving the file dictates them.

A CSV table with order_id, customer and total columns shown next to the XML elements each row produces

Problem 1: Column headers that aren’t valid names

CSV headers are written for humans. XML element names have rules, and a lot of real headers break them:

  • No spaces. Order ID can’t be a tag.
  • Can’t start with a digit. 2024 Sales is out.
  • Limited symbols. Price ($) and Qty # contain characters that aren’t allowed in names. Letters, digits, underscores, hyphens and dots are fine, but the name has to start with a letter or underscore.
  • Names starting with “xml” are reserved in any capitalisation, so avoid them.
  • Case matters. Total and total are different elements, which makes inconsistent headers a bigger problem than they are in CSV.

The usual fix is a small cleaning rule applied to every header: trim it, replace runs of invalid characters with an underscore, and add a leading underscore if the first character is a digit. Order ID becomes order_id, 2024 Sales becomes _2024_Sales, Price ($) becomes Price.

Duplicate headers are worth a look too. If two columns are both called phone, XML allows two <phone> elements in the same record, so the conversion won’t fail, but the receiving system may keep only one of them or reject the record. Rename them (phone_home, phone_work) so each one means something specific.

If the destination system expects specific tag names, which many import formats do, don’t guess. Get the spec or a sample file, and rename your CSV headers to match before converting. That’s far easier than debugging a rejected upload.

Problem 2: Characters that must be escaped

Some characters mean something to an XML parser, so they can’t appear as plain text inside an element. If they do, the file is no longer well-formed and the parser stops.

Table of XML special characters and their escaped forms, plus examples of cleaning invalid column headers

  • & must become &amp;. This is the one that bites most often, because names like “Smith & Sons” and URLs with query strings are everywhere.
  • < must become &lt;.
  • > should become &gt;. It’s only strictly required in one rare sequence, but escaping it always is the safe habit.
  • Quotes need to be &quot; or &apos; only inside attribute values, not in element text.

A converter that builds XML by sticking strings together will forget one of these sooner or later. A converter that uses a proper XML library handles it for you. This is the strongest reason to avoid hand-built XML, whether you’re writing code or choosing a tool.

There’s an alternative called a CDATA section, which wraps text in <![CDATA[ ... ]]> so that nothing inside needs escaping. It’s useful for large blocks of markup or code, but it can’t contain the sequence ]]>, and escaping is more widely understood. For ordinary CSV data, escape.

Problem 3: Invalid characters you can’t see

This one catches people who thought escaping covered everything. In XML 1.0, certain control characters aren’t allowed anywhere in a document, not even escaped. That covers most characters in the range 0 to 31, except tab, newline and carriage return.

They get into CSV files more often than you’d think: a stray null byte from a database export, a form-feed from copied text, an old system’s separator character. The XML looks fine to the eye and then a strict parser rejects the whole file with an error like “invalid character.”

The fix is to strip or replace those characters before writing the XML. If a file gets rejected with a vague character error, search the source for control characters. A text editor that can show invisible characters makes this easier.

Encoding is the other quiet failure. The declaration says encoding="UTF-8", so the file must actually be UTF-8. If the CSV came from a legacy system in Windows-1252, convert it first. Our guide to CSV encoding, UTF-8 and BOM problems shows how to tell, and how to fix it before it ends up in your XML.

Elements or attributes?

You can store a field as a child element or as an attribute:

<order id="1001"><customer>Ana Rao</customer></order>

versus

<order><id>1001</id><customer>Ana Rao</customer></order>

There’s no universal right answer, but a sensible rule is: use elements for data, attributes for short metadata. Elements can hold any text, including long or multi-line values and special characters. Attributes can’t hold multiple values or structure, and their quoting rules add one more thing to get wrong. IDs and codes make good attributes. Names, descriptions and notes should be elements.

Whichever you pick, apply it to every record. Mixed styles confuse the next person and break strict importers. And if the receiving system has a schema or a sample file, follow that over any rule of thumb.

A flat CSV has no hierarchy, but XML does, and some importers expect it. Say your file has street, city and postcode columns. The destination might want them wrapped together:

<customer>
  <name>Ana Rao</name>
  <address>
    <street>12 Lake Road</street>
    <city>Pune</city>
    <postcode>411001</postcode>
  </address>
</customer>

A plain converter won’t do this by itself, because nothing in the CSV says those three columns belong together. If you need nesting, you have two choices. Use a naming convention in the headers, like address.street, and a converter that splits on the dot, or write a small script that groups specific columns. The second is more work but gives you exact control. Either way, confirm the structure against the destination’s sample file, because a record that’s valid XML but has the wrong nesting is still rejected.

Empty cells and data types

CSV cells are often blank. XML gives you a few ways to show that:

  • An empty element: <phone></phone> or <phone/>. Both mean the same thing, and the element exists with no content.
  • Leaving the element out entirely. Smaller files, but now records have different shapes, and some importers insist on every field being present.
  • xsi:nil="true", which explicitly says “this is null” and is used in schema-driven systems.

Pick the one the importer wants. If you don’t know, an empty element is the usual middle ground.

For types, XML is text all the way down, just like CSV. 49.50 is a string until a schema says it’s a decimal. Dates should be in ISO 8601 (2026-11-13) because that’s what schema date types expect. Check numbers for thousands separators and currency symbols, which tend to arrive in CSV from a spreadsheet: 1,234.50 or ₹1,234.50 isn’t a valid decimal for most XML importers. Clean those columns first.

Namespaces, briefly

Some XML formats, product feeds and accounting imports especially, require a namespace on the root element, something like <feed xmlns="http://example.com/schema">. A namespace is just an identifier that says which vocabulary the element names belong to. You don’t need one for plain data exchange, but when the receiving system demands it, a document without it is treated as the wrong format entirely, even if every element name is right. If you’re given a sample file, check its root element carefully. Copy the namespace declaration exactly, including punctuation, because it’s compared as a string.

Convert CSV to XML in your browser

For a one-time job, a browser tool is the quickest route, and since these files often contain invoices, customer lists or payroll, it’s worth keeping the data on your device.

With the CSV to XML converter:

  1. Open the page and drop in your CSV.
  2. Check the preview of the parsed rows and the headers, and fix any odd ones.
  3. Set the root and row element names if the tool lets you, using whatever your destination system expects.
  4. Convert and download the XML.
  5. Validate the output (see below) before you upload it anywhere.

If your CSV has quoting problems, such as commas or line breaks inside fields, sort those out first. Our post on fixing comma and newline errors in CSV fields explains how. And for confidential files, the reasoning in why you shouldn’t upload sensitive CSVs to cloud converters applies doubly.

Converting with Python

If you do this regularly, a short script gives you full control. Python’s xml.etree.ElementTree escapes special characters automatically, which is exactly why it’s better than building strings:

import csv
import re
import xml.etree.ElementTree as ET

def tag(name):
    name = re.sub(r"[^A-Za-z0-9_.-]+", "_", name.strip()).strip("_")
    if not name or not re.match(r"[A-Za-z_]", name):
        name = "_" + name
    return name

root = ET.Element("orders")
with open("orders.csv", newline="", encoding="utf-8-sig") as f:
    for row in csv.DictReader(f):
        record = ET.SubElement(root, "order")
        for column, value in row.items():
            ET.SubElement(record, tag(column)).text = value

ET.indent(root)  # Python 3.9 and newer
ET.ElementTree(root).write("orders.xml", encoding="utf-8", xml_declaration=True)

utf-8-sig strips a byte order mark if the CSV has one, and csv.DictReader handles quoted fields properly. One caveat: ElementTree won’t remove control characters for you. If your data might contain them, clean each value first, for example with a regular expression that removes characters in the range \x00-\x08, \x0b, \x0c and \x0e-\x1f.

A messy row, step by step

Here’s the sort of row that causes trouble, taken from an imaginary supplier list:

Supplier Name,2024 Sales,Notes
"Smith & Sons <Ltd>",15000,"Pays late; ""priority"" account"

Walk through it. Supplier Name isn’t a legal tag, so it becomes supplier_name. 2024 Sales starts with a digit, so it becomes _2024_sales. The name contains &, < and >, so it comes out as Smith &amp; Sons &lt;Ltd&gt;. The notes cell has doubled quotes, which in CSV means literal quote marks, so the text is Pays late; "priority" account. In element text, those quotes don’t need escaping at all. The result:

<supplier>
  <supplier_name>Smith &amp; Sons &lt;Ltd&gt;</supplier_name>
  <_2024_sales>15000</_2024_sales>
  <notes>Pays late; "priority" account</notes>
</supplier>

Four small decisions in one row. Multiply that by ten thousand rows and you can see why doing the escaping by hand, or with find and replace, is a bad idea.

Check the XML before you use it

Two different checks matter here, and they get confused.

Well-formed means the file follows XML’s basic syntax: one root, properly closed tags, correct escaping, legal characters. Every parser needs this. The quickest test is to open the file in a browser, which will show an error with a line number if something’s wrong. On macOS and Linux, xmllint --noout orders.xml does the same from the terminal, and it’s silent when everything’s fine.

Valid means the file also matches a particular schema (an XSD) that defines which elements are allowed, in what order, with what types. Only the receiving system knows its rules, so if you have a schema, validate against it: xmllint --noout --schema orders.xsd orders.xml.

Then do a few quick sanity checks:

  • The number of record elements equals the number of CSV data rows.
  • Names with ampersands and accents came through correctly.
  • Blank cells appear the way the importer expects.
  • Numbers and dates look the way the destination wants them.
  • The file opens without errors in a browser or your editor.

If an upload still fails, the error message usually includes a line number. Open the file at that line and look closely. Nine times out of ten it’s one of the three problems above.

Big files and readable output

XML is wordy. Every value is wrapped in an opening and closing tag, so the file is usually several times larger than the CSV it came from. A 20 MB CSV can easily become 80 MB or more of XML. That’s fine for a server, but it can make a browser or an editor struggle, and some upload forms have size limits. If the destination has a limit, ask whether it accepts compressed files or can take the data in batches, and split the CSV before converting if it can’t. Our guide on opening large CSV files that Excel can’t handle has practical ways to split files.

Indentation is optional for parsers and costs file size, so production feeds are often written without it. For files you’ll inspect yourself, keep the indentation. It makes errors much easier to find.

The short version

CSV to XML is a simple mapping, and almost every failure comes from the details: header names that aren’t legal, characters that aren’t escaped, and hidden control characters. Clean the headers, let a real XML library do the escaping, check the encoding, and validate the output before you upload it. Then the conversion is boring, which is exactly what you want.

Frequently asked questions

How does a CSV file map to XML?

Each row becomes a repeating record element, each column header becomes the name of a child element, and each cell value becomes that element's text. All the records sit inside one root element, because an XML document must have exactly one top-level element.

Why does my CSV to XML conversion fail on some column names?

XML element names can't contain spaces, can't start with a digit or punctuation mark, and can't include many symbols. A header like Order ID or 2024 Sales has to be cleaned up, for example to order_id and _2024_Sales, before it can be used as a tag name.

Which characters need to be escaped in XML?

The ampersand and the less-than sign must always be escaped as &amp; and &lt;. The greater-than sign is usually escaped as &gt; for safety, and quotes need escaping as &quot; or &apos; inside attribute values. Alternatively, wrap text in a CDATA section, though escaping is simpler and more widely supported.

Should CSV columns become XML elements or attributes?

Elements are the safer default because they can hold any text, including long values and special characters, and they're easier for other systems to extend. Attributes suit short metadata like an ID or a type. Mixing both is fine as long as you pick a rule and apply it to every record.

Is it safe to convert confidential CSV data to XML online?

Not if the converter uploads your file. For customer lists, invoices or internal records, use a tool that runs entirely in your browser so the data never leaves your device. RealCSVTools converts locally using client-side JavaScript.