3 min read
By HappyCSV Team

Convert CSV to XML (For Legacy Systems)

How to convert CSV files to XML format. Understand elements vs attributes, schema validation, and tools for conversion.

Convert CSV to XML (For Legacy Systems)

XML (eXtensible Markup Language) is the grandfather of data interchange. While JSON has taken over the web, XML is still king in enterprise, banking (SEPA), and legacy systems.

Converting CSV to XML isn't just about changing delimiters. You have to define a structure.

The Structure Choice: Elements vs Attributes

CSV Input:

id,name
1,John

Option A: Elements (Most Common)

<records>
  <row>
    <id>1</id>
    <name>John</name>
  </row>
</records>

Option B: Attributes (More Compact)

<records>
  <row id="1" name="John" />
</records>

You need to know which format your target system expects.

Method 1: Python Script

Python is great for this because it handles the loop easily.

import csv

csvFile = 'data.csv'
xmlFile = 'data.xml'

csvData = csv.reader(open(csvFile))
xmlData = open(xmlFile, 'w')

xmlData.write('<?xml version="1.0"?>' + "\n")
xmlData.write('<csv_data>' + "\n")

rowNum = 0
for row in csvData:
    if rowNum == 0:
        tags = row
        # replace spaces in tags with underscores
        tags = [x.replace(' ', '_') for x in tags]
    else:
        xmlData.write('<row>' + "\n")
        for i in range(len(tags)):
            xmlData.write('    ' + '<' + tags[i] + '>' \
                          + row[i] + '</' + tags[i] + '>' + "\n")
        xmlData.write('</row>' + "\n")
    rowNum +=1

xmlData.write('</csv_data>' + "\n")
xmlData.close()

Method 2: Excel (Developer Tab)

Excel has powerful XML mapping features, but they are hidden.

  1. Enable Developer Tab (File > Options > Customize Ribbon).
  2. Create an XML Schema file (.xsd) or a sample XML file that matches your desired structure.
  3. Developer > Source.
  4. Click XML Maps and add your sample XML.
  5. Drag and drop the XML nodes onto your Excel columns to map them.
  6. Developer > Export.

This is complex but gives you perfect control over the output structure.

Method 3: Online Converters

For quick, standard conversions (Elements style).

-> Convert CSV to XML

Special Characters

XML is strict. You cannot have < > & inside your data.

CSV: John & Sons XML: <name>John &amp; Sons</name>

Your converter must escape these characters, or the XML will be invalid.

  • & -> &amp;
  • < -> &lt;
  • > -> &gt;
  • " -> &quot;
  • ' -> &apos;

Summary

  • Decide: Elements or Attributes?
  • Ensure headers are valid XML tags (no spaces, don't start with numbers).
  • Escape special characters.
  • Use Python for automation, or Excel for complex schema mapping.

Need XML? HappyCSV converts CSV to XML instantly, handling escaping and tag generation automatically.

Need to handle CSV files?

HappyCSV is the free, secure way to merge, split, and clean your data — all in your browser.