How to Convert XML to CSV: The Complete Guide
XML and CSV solve different problems. XML stores relationships, attributes, and nested content, while CSV gives spreadsheet applications a rectangular table. Converting between them is therefore a decision about the meaning of your data as well as a change of file format. A customer address nested inside an order can become several columns. Repeated line items can become several rows. Choosing those rules before exporting prevents missing values and misleading reports.
This guide explains four practical routes: a browser converter, Windows desktop Excel, Python, and command line utilities. Each route can be useful, but the best choice depends on your source structure and how often you repeat the work. Start with a small representative file, inspect the output, and keep the original XML. Conversion creates a useful table; it does not preserve every feature of the source document.
For a quick conversion, use the free online XML to CSV converter. Processing takes place locally in your browser. You can review the record element, select fields, and inspect a preview before downloading. No account or file upload to a remote conversion service is needed.
Understanding XML and CSV Formats
What is XML?
XML represents information using named elements. An opening tag starts an element, a closing tag ends it, and attributes carry additional values on the opening tag. Elements can contain text, other elements, or both. A catalog might contain books, and each book might contain a title, price, and several authors. The structure communicates relationships that are implicit in a spreadsheet.
Element names may include namespace prefixes. A prefix is a shorthand for a namespace URI, rather than an arbitrary decoration. Two elements with the same local name can belong to different namespaces. Preserve that distinction when choosing fields. XML declarations can also identify the character encoding; save inputs as UTF-8 before using this converter.
What is CSV?
CSV is a text representation of rows and columns. A header usually supplies column names, although some importers require data without a header. Commas are conventional separators, but related delimited formats use tabs, semicolons, or pipes. A value containing a separator, double quote, or newline must be quoted correctly. Quotes inside a quoted value are doubled.
A CSV file does not define types reliably. A spreadsheet may reinterpret an identifier as a number, a long integer as scientific notation, or a date according to local settings. When preserving identifiers matters, import the CSV through an explicit import dialog and choose text columns. Review leading zeroes and international characters after importing.
Key Differences Between XML and CSV
The most important difference is hierarchy. XML can hold several related collections inside one record; CSV requires a row model. Flattening parent and child names produces readable headers, but repeated collections still require an expansion rule. XMLtoCSV uses Cartesian expansion for different repeated child groups, preserving parent values in every resulting row.
CSV also omits XML comments, processing instructions, namespace declarations as business fields, and document formatting. Mixed content needs special attention: direct text and child element text have different meanings. If you need nested markup intact, disable flattening and review the resulting compact XML or JSON array strings instead of expanding them.
Method 1: Using an Online Converter (Recommended)
Step-by-Step Guide
- Open the XML to CSV converter and wait for the offline readiness message.
- Choose Upload File and browse for an XML file, or choose Paste XML and paste the document.
- Inspect Record element. The inferred path is a starting point; select a different element if your business records live deeper in the document.
- Review Select Fields. Expand branches, remove unnecessary columns, and check the record count.
- Set your delimiter, header preference, quote preference, flattening mode, and spreadsheet formula protection.
- Inspect the first twenty rows, then select Download CSV to export the complete result.
The standard input limit is 10MB per file, using binary megabyte boundaries internally. Pasted content is limited to 500,000 Unicode code points. A rejected or malformed replacement input invalidates the previous download, so you cannot accidentally export stale results. Clear asks for confirmation and removes current input and results from memory.
Handling Nested XML Elements
A field such as an order customer name becomes a column with an underscore-separated path. Attributes use an @ marker. Repeated children generate separate rows while retaining ancestor values. If two items and three tags occur inside one record, their combinations produce six rows. This is useful for relationship exports, but it can increase output size quickly.
Select a deeper Record element when you want one row per child rather than one row per combination. Ancestor values above that selected element are not exported. Compare a few known records with the preview before deciding. The nested XML converter explains the same workflow for hierarchical documents and provides a dedicated entry point.
Choosing the Right Delimiter
Choose the delimiter expected by the destination application. Commas work with many databases and spreadsheets. Semicolons are common in some regional workflows, while tabs can simplify reading text containing many commas. Pipe delimiters are useful only when the receiving importer supports them explicitly. Changing the delimiter does not remove the need for proper escaping.
Keep formula protection enabled for untrusted files. It prefixes potentially executable spreadsheet values with an apostrophe, including negative values. The preview shows that apostrophe. If exact original strings are required and the source is trusted, turn protection off deliberately and inspect the regenerated output. Quoting a CSV value by itself does not prevent spreadsheet formula execution.
Method 2: Converting XML to CSV in Excel
Using Excel's Built-in XML Import
For Windows desktop Excel 2019, Excel 2021, and Microsoft 365, Power Query provides a practical import route. Open Data, then Get Data, From File, and From XML. Select the source and choose Transform Data. Expand the Table and Record columns that correspond to your desired records, checking row counts after every expansion.
When the table is ready, choose Close & Load. Review the worksheet and save the active sheet using File, Save As, CSV UTF-8 (Comma delimited). That format exports the active sheet only. Keep a separate workbook copy if you need transformations, formulas, or multiple sheets later. Reopen the CSV through an import dialog to verify text identifiers and encoding.
Limitations of the Excel Method
XML Maps offer a second route through Developer, Source, XML Maps, and Add. A compatible XSD makes mapping clearer. Without one, inferred mappings may not express the source correctly, particularly when repeated elements appear at several levels. Drag mapped nodes into a worksheet and use Developer, Import to populate the table.
Excel is familiar, but its worksheet row limits, memory use, schema restrictions, and automatic type conversion can complicate large or irregular XML. Mac and web interfaces differ from these Windows instructions. Follow the Excel conversion tutorial for a more detailed explanation of both supported desktop workflows.
Method 3: Using Python for XML to CSV Conversion
Basic Conversion with ElementTree
Python is appropriate when you need a repeatable schema-specific transformation. The standard library includes an XML parser and a CSV writer, so a straightforward script needs no additional package. Specify fields explicitly rather than taking the first record as a complete schema. Otherwise a field that appears only in a later record can disappear silently.
The following complete example uses a controlled catalog schema. It preserves an attribute, supplies an empty string for missing prices, and delegates quoting to csv.writer. The included fixture contains commas, double quotes, and Unicode. Run it with Python 3.12. The input, command, and expected output are shown with the script.
Complete input XML
<catalog><book id="0001"><title>Tea, "雪"</title><price>12.50</price></book><book id="0002"><title>Café</title></book></catalog>Complete Python script
import csv
import sys
import xml.etree.ElementTree as ET
def main():
source = sys.argv[1] if len(sys.argv) > 1 else "catalog.xml"
destination = sys.argv[2] if len(sys.argv) > 2 else "output.csv"
try:
root = ET.parse(source).getroot()
with open(destination, "w", encoding="utf-8-sig", newline="") as output:
writer = csv.writer(output)
writer.writerow(["book_@id", "book_title", "book_price"])
for book in root.findall("book"):
writer.writerow([book.get("id", ""),
book.findtext("title", default=""),
book.findtext("price", default="")])
except (OSError, ET.ParseError) as error:
print(f"Conversion failed: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
Run
python basic.pyExpected CSV output
book_@id,book_title,book_price
0001,"Tea, ""雪""",12.50
0002,Café,
This script assumes that each book is a direct child of catalog. It does not claim to flatten arbitrary XML. Adapt the record search and fields deliberately for your own schema. A missing input, malformed XML, or unwritable destination exits with a nonzero status so automation can detect failure rather than accepting an incomplete export.
Using pandas for Complex XML
pandas is useful when conversion is followed by joins, filters, or aggregation. Extract XML records explicitly, construct dictionaries with a known column set, and create a DataFrame from those dictionaries. Then export using to_csv with index disabled and a deliberate encoding. This keeps XML relationship decisions visible instead of hiding them inside automatic inference.
See the Python XML to CSV guide for complete pandas, lxml, and incremental parsing examples. A DataFrame holds its data in memory, so it is not automatically a streaming solution. For a very large export, write one record at a time with iterparse and clear completed elements.
Method 4: Command Line Tools
Using xmlstarlet
xmlstarlet is effective when you know the exact XPath and namespace bindings. For the catalog fixture used here, select book elements as XML fragments first. Then let a complete Python program parse the fragments and emit CSV. Directly joining XPath values with commas is unsafe because values may themselves contain commas, quotes, or newlines.
Complete input XML
<catalog><book id="0001"><title>Tea, "雪"</title><price>12.50</price></book><book id="0002"><title>Café</title></book></catalog>Complete Python script
import csv
import sys
import xml.etree.ElementTree as ET
def main():
source = sys.argv[1] if len(sys.argv) > 1 else "fragments.xml"
destination = sys.argv[2] if len(sys.argv) > 2 else "output.csv"
try:
root = ET.fromstring("<catalog>" + open(source, encoding="utf-8").read() + "</catalog>")
with open(destination, "w", encoding="utf-8-sig", newline="") as output:
writer = csv.writer(output)
writer.writerow(["book_@id", "book_title", "book_price"])
for book in root.findall("book"):
writer.writerow([book.get("id", ""),
book.findtext("title", default=""),
book.findtext("price", default="")])
except (OSError, ET.ParseError) as error:
print(f"Conversion failed: {error}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
Run
xmlstarlet sel -t -m "/catalog/book" -c "." -n catalog.xml > fragments.xml
python fragments.pyExpected CSV output
book_@id,book_title,book_price
0001,"Tea, ""雪""",12.50
0002,Café,
The XPath selects only the controlled catalog structure. A namespaced catalog requires an explicit namespace binding and a matching XPath. An unexpected wrapper, renamed record, or different namespace changes the query. Treat an empty selection as something to investigate, and verify expected record counts before using the CSV in a report.
Using csvkit
csvkit does not provide a universal direct XML import in this workflow. First extract the controlled records into a JSON object array using the complete script below. Then run in2csv with its JSON format option. The intermediate JSON makes field choices explicit and allows the CSV tool to handle quoting consistently.
Complete input XML
<catalog><book id="0001"><title>Tea, "雪"</title><price>12.50</price></book><book id="0002"><title>Café</title></book></catalog>Complete Python script
import json
import sys
import xml.etree.ElementTree as ET
try:
root = ET.parse("catalog.xml").getroot()
rows = [{"book_@id": b.get("id", ""),
"book_title": b.findtext("title", default=""),
"book_price": b.findtext("price", default="")}
for b in root.findall("book")]
with open("records.json", "w", encoding="utf-8") as output:
json.dump(rows, output, ensure_ascii=False)
except (OSError, ET.ParseError) as error:
print(f"Extraction failed: {error}", file=sys.stderr)
raise SystemExit(1)
Run
python extract-json.py
in2csv -f json records.json > records.csvExpected CSV output
book_@id,book_title,book_price
1,"Tea, ""雪""",12.50
2,Café,
csvkit infers numeric types here: 0001 becomes 1, as shown in the expected output. Use its no-inference option in a customized command if exact string formatting is required. Pin csvkit to the tested version when using this in automation. Keep the extraction script, input fixture, and expected output in the same repository. A tool upgrade can change defaults, so rerun comparison tests before replacing a production job. Do not assume a command that handles this fixture understands every XML schema.
Choosing the Right Method
| Method | Best use | Main consideration |
|---|---|---|
| Browser converter | Occasional private conversions | Review row expansion and file limits |
| Windows Excel | Spreadsheet preparation | Control import types and nested expansion |
| Python | Repeated or custom processing | Maintain and test schema-specific code |
| Command line tools | Scripted extraction | Make XPath and escaping rules explicit |
For a one-off task, the browser tool removes setup and gives an immediate preview. For a recurring supplier feed, a tested Python script provides clearer control over schema changes and failures. Excel fits teams already reviewing data in workbooks. Command line utilities work well as components in an existing scripted pipeline, provided their assumptions are documented.
Common Challenges and Solutions
Handling Nested Elements
Decide what a row represents before exporting. If an order has multiple items and multiple discounts, combining every group may produce more rows than expected. Inspect source records with known counts and compare those counts with the output. Deselecting a field changes columns, not the underlying expansion rule. Choose another record element when necessary.
Dealing with Attributes
Attributes frequently carry identifiers, currency codes, and category names. Omitting them can make an otherwise readable export unusable. Keep attribute columns separate from similarly named child elements. The attribute conversion guide shows how to combine both sources without collisions or accidental overwrites.
Managing Large Files
Use the large file converter for inputs up to 50MB. It scans the complete file to discover fields before conversion and displays progress. Expanded output still has row, output byte, and per-record memory limits. If a record is too large, select a deeper record element or split the source using a schema-aware process.
Character Encoding Issues
Use UTF-8 consistently. A byte order mark on the CSV helps Excel recognize Unicode, but it does not fix incorrectly decoded source data. Check names containing accented or non-Latin characters in both preview and destination. Do not remove characters merely to make an encoding error disappear; correct the source encoding instead.
Conclusion
A reliable conversion starts with a clear row model, explicit fields, correct CSV escaping, and a small validation sample. Keep the source, verify representative records, and confirm the destination's import settings. For an immediate local workflow, start converting XML to CSV and review the preview before downloading your file.