Spreadsheet formats & CSV
How To Convert CSV To XML In Python?
Parse CSV rows and build an XML tree using ElementTree, with an explicit mapping from columns to XML elements.
Parse CSV rows and build an XML tree using ElementTree, with an explicit mapping from columns to XML elements. XML has names, nesting and namespaces; CSV headers alone do not define the XML schema a recipient requires.
Set up the conversion
The example accepts exactly id, name and note, and represents every CSV field as text under a row element. ElementTree escapes XML-sensitive characters when it serializes the tree. Using a fixed mapping avoids placing arbitrary header strings into element names, where spaces or punctuation may make an invalid document.
A reproducible conversion example
import csv
import xml.etree.ElementTree as ET
root = ET.Element("records")
with open("input.csv", encoding="utf-8-sig", newline="") as source:
reader = csv.DictReader(source)
fields = ["id", "name", "note"]
if reader.fieldnames != fields:
raise ValueError("Expected id,name,note headers in that order")
for record in reader:
if None in record or any(v is None for v in record.values()):
raise ValueError("Wrong field count")
row = ET.SubElement(root, "row")
for field in fields:
ET.SubElement(row, field).text = record[field]
ET.ElementTree(root).write("output.xml", encoding="utf-8", xml_declaration=True)The code is an illustrative conversion core. Run it in an isolated working folder with the named test files, install only the dependencies used by the example, and handle its reported errors before applying it to a larger dataset. It does not contact a remote conversion service.
Check the expected result
Test a note containing A & B and a less-than sign. The serialized file must escape those characters, while parsing the XML again must restore the original text. Count row elements and check id values such as 00123. Empty CSV strings serialize as empty elements; if your schema distinguishes empty from absent, define that rule and test it explicitly.
Format-specific limits
A well-formed XML document is not automatically valid for a business schema. If the recipient supplies an XSD, match its element names, ordering, namespaces and required attributes, then validate with an XSD-capable validator. Do not claim that this generic records/row layout is compatible with an unrelated import system.
Verify the file contract before using the result
Write down the delimiter, encoding, header names, field order and treatment of empty values. Keep the original file unchanged and write the converted output to a different path. Conversion is successful when a parser for the destination format recovers the intended values; a familiar filename extension or a successful save message is not enough.
Start with a small fixture that contains the cases your real data can contain. Include a leading-zero identifier, a quoted comma, an embedded quotation mark, a blank field and a non-ASCII character. Add a multiline field only if both formats and the receiving system support it. Verify the fixture first, then run a bounded sample from the real input. Record parsed row counts and check the first and last records so truncation or an accidental duplicate header is visible.
Keep identifiers separate from quantities. An account-like or product identifier may contain digits while still being text; converting it to a floating-point number can remove leading zeros or precision. Dates also need an agreed format. When a conversion produces an unexpected blank, investigate whether it came from an empty source cell, a missing field, an invalid value or an automatic missing-value rule. Those conditions can require different downstream handling.
Do not resolve malformed records by silently skipping them unless that behavior is an explicit requirement and the skipped records are reported. Use a failure message that identifies the record or field, retain enough context to correct the input, and avoid exposing sensitive contents in public logs. For production automation, write to a temporary destination and promote it only after validation so a failed run cannot replace a previously good export.
Where the browser tool fits
Convert Text to CSV helps with already extracted plain text. It does not replace a workbook reader, a JSON parser, an XML schema validator or a Parquet engine. Use it only when its input structure and delimiter choices match your actual data. For structured source files, perform the format-aware conversion above and check the result with an independent reader.
Primary reference
Official format and API documentation


