ToolDeck

CSV to XML

Convert CSV data to XML format

Try an example

CSV Input

XML Output

Runs locally · Safe to paste secrets
XML output will appear here…

What is CSV to XML Conversion?

CSV to XML conversion transforms comma-separated values into Extensible Markup Language (XML) documents. Each row of the CSV becomes an XML element, and each column header maps to a child element tag name. The result is a hierarchical, self-describing document that systems can validate against a schema (XSD or DTD) and process with standard XML tooling such as XSLT, XPath, and SAX/DOM parsers.

XML has been a data interchange standard since the W3C published the XML 1.0 specification in 1998. While JSON has replaced XML in many web APIs, XML remains the required format for SOAP web services, RSS/Atom feeds, SVG graphics, Office Open XML documents (.docx, .xlsx), Android resource files, Maven/Gradle build configs, and regulated industries like healthcare (HL7 CDA), finance (FpML, XBRL), and government (NIEM). When your source data is a spreadsheet or database export, CSV-to-XML conversion is how you get it into these systems.

A correct CSV to XML converter must handle RFC 4180 edge cases: quoted fields containing commas or newlines, escaped double quotes, and varying delimiters. On the XML side, it must escape the five predefined XML entities (& < > " '), generate valid element names from headers (replacing spaces and special characters), and produce well-formed output with a proper XML declaration and consistent encoding.

Why Use a CSV to XML Converter?

Writing XML by hand from spreadsheet data is slow and error-prone. Missing a closing tag or forgetting to escape an ampersand produces invalid XML that breaks downstream parsers. This converter handles parsing, escaping, and element generation in a single step.

Convert instantly in your browser
Paste CSV and get well-formed XML output with a proper declaration, root element, and nested child elements. No command-line tools or library installs needed.
🔒
Keep data private
All conversion runs locally in your browser using JavaScript. Your CSV data is never uploaded to a server, never logged, and never stored anywhere outside your machine.
🎯
Generate valid, well-formed XML
The output escapes XML entities, sanitizes header names into valid element tags, and produces properly nested markup that passes any XML validator or linter.
📋
Handle any CSV dialect
Auto-detects commas, semicolons, tabs, and pipes as delimiters. Supports RFC 4180 quoting rules including escaped double quotes, multiline fields, and BOM-prefixed UTF-8 files.

CSV to XML Use Cases

SOAP and legacy API integration
Many enterprise systems still use SOAP web services that require XML request bodies. Convert a CSV data export into XML payloads that match the service's WSDL schema before sending requests.
Build configuration files
Generate Maven pom.xml dependency lists, Android resource files, or Spring bean definitions from a spreadsheet of dependencies, strings, or config entries. Batch-produce XML configs from a single CSV source.
Data pipeline ETL
Feed CSV exports from databases or analytics tools into XML-based ETL pipelines. Tools like Apache NiFi, Talend, and SSIS accept XML inputs for transformation workflows that require schema validation at each stage.
Regulatory and compliance reporting
Industries like healthcare (HL7 CDA), finance (XBRL, FpML), and government (NIEM) mandate XML-formatted submissions. Convert tabular compliance data into the required XML structure before submission.
RSS and Atom feed generation
Turn a CSV list of articles, titles, and dates into an RSS 2.0 or Atom feed. Content management workflows often start with a spreadsheet of posts that need to be published as a syndication feed.
Teaching XML fundamentals
Students learning XML can paste familiar CSV data and see the resulting element hierarchy, nesting, and entity escaping. Comparing input and output makes abstract concepts like well-formedness and validity concrete.

CSV to XML Mapping Reference

Understanding how each part of a CSV file maps to XML structure helps you predict the output format and adjust your data before conversion.

CSV ConceptXML EquivalentDetails
CSV fileXML documentThe entire file maps to a root element containing all records
Header rowElement tag namesEach column header becomes the tag name for child elements
Data row<row> elementEach row becomes a repeating child element of the root
Cell valueText nodeCell content becomes the text inside the corresponding tag
Empty cellEmpty element or omittedCan be rendered as <field/> or excluded from output
Comma delimiterXML structureDelimiters are replaced by element nesting and closing tags

CSV vs XML

CSV is a flat, delimiter-based format with no built-in schema or data types. XML is a hierarchical, self-describing markup language that supports schemas, namespaces, and complex nesting. Choosing between them depends on your downstream system requirements.

CSV
Plain text, one record per line. No data types: every value is a string. No hierarchy or nesting. Minimal file size. Universally supported by spreadsheets, databases, and scripting languages. Defined by RFC 4180. Best for simple tabular data transfer between systems that both understand the column layout.
XML
Hierarchical markup with opening and closing tags. Supports attributes, namespaces, mixed content, and CDATA sections. Can be validated against XSD or DTD schemas. Processed by XSLT, XPath, SAX, and DOM parsers. Larger file size than CSV due to tag overhead. Required by SOAP APIs, Office Open XML, RSS/Atom, and many regulated industries.

Code Examples

Below are working examples of CSV to XML conversion in different languages. Each example parses the CSV header row as element tag names, wraps each data row in a container element, and escapes XML entities in cell content.

JavaScript (browser / Node.js)
// CSV string → XML with proper escaping
const csv = `name,age,city
Alice,30,Berlin
Bob,25,Tokyo`

function csvToXml(csv, rootTag = 'data', rowTag = 'row') {
  const rows = csv.trim().split('\n').map(r => r.split(','))
  const [headers, ...data] = rows
  const xmlRows = data.map(row => {
    const fields = headers.map((h, i) => {
      const val = (row[i] || '').replace(/&/g, '&amp;')
        .replace(/</g, '&lt;').replace(/>/g, '&gt;')
      return `    <${h}>${val}</${h}>`
    }).join('\n')
    return `  <${rowTag}>\n${fields}\n  </${rowTag}>`
  }).join('\n')
  return `<?xml version="1.0" encoding="UTF-8"?>\n<${rootTag}>\n${xmlRows}\n</${rootTag}>`
}

console.log(csvToXml(csv))
// → <?xml version="1.0" encoding="UTF-8"?>
// → <data><row><name>Alice</name><age>30</age>...</row>...</data>
Python
import csv, io
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom.minidom import parseString

csv_string = """name,age,city
Alice,30,Berlin
Bob,25,Tokyo"""

reader = csv.DictReader(io.StringIO(csv_string))
root = Element('data')

for row in reader:
    row_el = SubElement(root, 'row')
    for key, value in row.items():
        child = SubElement(row_el, key)
        child.text = value

# Pretty-print with declaration
raw = tostring(root, encoding='unicode')
pretty = parseString(raw).toprettyxml(indent='  ')
print(pretty)
# → <?xml version="1.0" ?>
# → <data>
# →   <row>
# →     <name>Alice</name>
# →     <age>30</age>
# →     <city>Berlin</city>
# →   </row>
# →   ...
# → </data>
Go
package main

import (
	"encoding/csv"
	"encoding/xml"
	"fmt"
	"os"
	"strings"
)

type Field struct {
	XMLName xml.Name
	Value   string `xml:",chardata"`
}

type Row struct {
	XMLName xml.Name `xml:"row"`
	Fields  []Field
}

type Data struct {
	XMLName xml.Name `xml:"data"`
	Rows    []Row
}

func main() {
	input := "name,age,city\nAlice,30,Berlin\nBob,25,Tokyo"
	r := csv.NewReader(strings.NewReader(input))
	records, _ := r.ReadAll()
	headers := records[0]

	var data Data
	for _, rec := range records[1:] {
		row := Row{}
		for i, h := range headers {
			row.Fields = append(row.Fields, Field{
				XMLName: xml.Name{Local: h},
				Value:   rec[i],
			})
		}
		data.Rows = append(data.Rows, row)
	}

	out, _ := xml.MarshalIndent(data, "", "  ")
	fmt.Println(xml.Header + string(out))
	// → <?xml version="1.0" encoding="UTF-8"?>
	// → <data><row><name>Alice</name>...</row>...</data>
}
CLI (csvkit / xmlstarlet)
# Using Python's csv and xml modules via one-liner
python3 -c "
import csv, sys
from xml.etree.ElementTree import Element, SubElement, tostring
from xml.dom.minidom import parseString

reader = csv.DictReader(sys.stdin)
root = Element('data')
for row in reader:
    r = SubElement(root, 'row')
    for k, v in row.items():
        SubElement(r, k).text = v
print(parseString(tostring(root, encoding='unicode')).toprettyxml(indent='  '))
" < data.csv

# Using Miller (mlr) — a dedicated CSV/JSON/XML tool
mlr --icsv --oxml cat data.csv

Frequently Asked Questions

How does CSV to XML conversion work?
The converter reads the first row of your CSV as column headers. Each subsequent row becomes an XML element, and each cell value is wrapped in a child element named after its column header. The result is a well-formed XML document with a root element containing one child element per data row.
What happens to special characters like & and < in my CSV data?
The converter escapes all five XML predefined entities: & becomes &amp;, < becomes &lt;, > becomes &gt;, " becomes &quot;, and ' becomes &apos;. This produces valid XML that will not break parsers or cause well-formedness errors.
Can I use custom tag names for the root and row elements?
Yes. The tool lets you set the root element name (default: "data") and the row element name (default: "row"). Column headers from the CSV always become the child element names. If a header contains spaces or characters that are invalid in XML element names, the tool sanitizes them automatically.
What is the difference between CSV to XML and CSV to JSON?
CSV to XML produces a hierarchical markup document with opening/closing tags, an XML declaration, and support for schema validation (XSD/DTD). CSV to JSON produces a lighter-weight array of key-value objects. Use XML when your target system requires it (SOAP APIs, regulated formats, RSS feeds). Use JSON for REST APIs, JavaScript frontends, and NoSQL databases.
How do I validate the generated XML output?
Paste the output into any XML validator to check well-formedness (correct nesting, proper entity escaping, matching tags). For schema validation, provide an XSD file and use a tool like xmllint, Xerces, or an online XSD validator. The XML produced by this tool is always well-formed, but schema validity depends on whether the structure matches your target schema.
Does the converter handle large CSV files?
The tool runs in your browser, so performance depends on available memory. Files up to a few megabytes (tens of thousands of rows) convert without issues on modern hardware. For very large files (100MB+), consider a command-line tool like Python's csv and xml.etree modules or Go's encoding/csv and encoding/xml packages, which process data as a stream without loading everything into memory.
Is the generated XML compatible with XSLT transformations?
Yes. The output is standard well-formed XML with a declaration and consistent element structure. You can apply any XSLT stylesheet to transform it into HTML, another XML schema, or plain text. The predictable structure (root > row > field elements) makes writing XPath selectors and XSLT templates straightforward.