Convert XML to CSV with Python

Python makes XML conversion repeatable. Its standard library can parse structured documents and write correctly escaped CSV, while pandas and lxml add tools for analysis and precise selection. The important work is defining the records and fields. A converter that appears to work on one sample can still lose identifiers, ignore later fields, or duplicate rows when the structure changes.

This tutorial uses a small catalog fixture so every example can be executed and compared with a known result. The fixture deliberately includes punctuation, Unicode, a missing value, and an attribute. Each script has an explicit schema, rather than claiming to convert arbitrary XML. If you only need a one-off export, the browser XML to CSV converter provides field selection without installing Python packages.

Prerequisites and Setup

Use Python 3.12 as the baseline. Create a project directory and a virtual environment, activate it, and save the fixture as catalog.xml. The ElementTree and incremental examples use the standard library. For the other examples install the exact tested packages: pandas 2.2.3 and lxml 5.3.0. Keeping a virtual environment avoids changing packages used by unrelated applications.

Run each script from the directory containing the fixture, or pass input and output paths explicitly. Do not overwrite your original XML. Keep generated files in a separate directory when developing a recurring job. A conversion script should fail visibly when the source is missing or malformed, rather than silently producing a header-only report that looks successful.

The examples write UTF-8 with a byte order mark for spreadsheet compatibility and use Python's CSV facilities to escape values. Their output retains exact source values; unlike the browser tool's default, they do not add spreadsheet formula protection. For untrusted inputs, treat values beginning with formula characters as potentially unsafe before opening the result in a spreadsheet.

Method 1: Using xml.etree.ElementTree

Basic Conversion Script

ElementTree is a good starting point for a known structure. Parse the document, select its direct book children, extract the id attribute and named child elements, then write rows through csv.writer. Using explicit field names avoids relying on element order or on the first record having every possible field. Missing elements become empty strings in this example.

A title containing a comma must remain one cell, and a title containing quotes must round-trip without losing them. csv.writer handles those details. Opening the output with newline set to an empty string prevents extra newline translation on Windows. The encoding utf-8-sig writes the BOM expected by many spreadsheet workflows without changing the text values.

Complete Code Example

Save the complete script below as basic.py. Create catalog.xml from the included fixture and run the displayed command. The expected output uses CRLF record separators; your editor may display them as ordinary line breaks. Compare logical CSV values with csv.reader rather than assuming visual punctuation alone proves a correct export.

Complete input XML

<catalog><book id="0001"><title>Tea, &quot;雪&quot;</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.py

Expected CSV output

book_@id,book_title,book_price
0001,"Tea, ""雪""",12.50
0002,Café,

The script catches operating system errors and XML syntax errors, writes a short diagnostic to standard error, and returns a nonzero exit code. Check that status in a scheduled job or shell pipeline. For production automation, also write to a temporary destination and rename it only after the conversion completes, so downstream consumers cannot read an incomplete file.

Handling Attributes

Attributes are accessed through the element's attrib mapping or get method. They are separate from child elements. A book id attribute and an id child can coexist and may mean different things, so assign different output columns. Do not merge attribute and child dictionaries without explicit prefixes, because a collision can overwrite a useful value without raising an error.

Namespaced attributes require expanded names such as a namespace URI in braces followed by the local name. Unprefixed attributes usually remain outside the default element namespace. This distinction is easy to miss when a feed adds namespaces later. Add a fixture for that change and verify your selectors before running the updated export against the full feed.

Method 2: Using pandas with xml.etree

Leveraging pandas DataFrame

pandas is helpful when the next step is analysis. Explicit extraction gives you a list of dictionaries with stable keys, and DataFrame provides filtering, joins, grouping, and export. Supply a column list so output order is stable, including for empty input. Disable the index during CSV export unless an index column is part of your intended data contract.

Be careful with type inference. Numeric identifiers, postal codes, and account numbers may need to stay strings. Converting them to integers can discard leading zeroes. Missing values also deserve a deliberate rule: the example uses empty strings, but a downstream database might distinguish missing from empty. Document that choice alongside the extraction code.

Code Example

This complete example uses pandas 2.2.3. Its XML parsing step is explicit, so you can see exactly which records and fields enter the DataFrame. It does not use a generic automatic flattening rule. The fixture, execution command, and expected output accompany the script for straightforward local verification.

Complete input XML

<catalog><book id="0001"><title>Tea, &quot;雪&quot;</title><price>12.50</price></book><book id="0002"><title>Café</title></book></catalog>

Complete Python script

import pandas as pd
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()
        records = [{"book_@id": book.get("id", ""),
                    "book_title": book.findtext("title", default=""),
                    "book_price": book.findtext("price", default="")}
                   for book in root.findall("book")]
        frame = pd.DataFrame(records, columns=["book_@id", "book_title", "book_price"])
        frame.to_csv(destination, index=False, encoding="utf-8-sig", lineterminator="\r\n")
    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 -m pip install pandas==2.2.3
python convert-pandas.py

Expected CSV output

book_@id,book_title,book_price
0001,"Tea, ""雪""",12.50
0002,Café,

A DataFrame stores its rows in memory. That is convenient for modest analysis datasets but can be expensive for very large XML files. Avoid building a list of every record if the only task is writing a CSV. The incremental method below writes rows as they are encountered and releases XML elements after extracting their values.

Method 3: Using lxml for Complex XML

When to Use lxml

lxml provides XPath, mature namespace support, and efficient parsing. It is useful when a schema requires precise selection across a hierarchy or when you already use XPath expressions elsewhere. Use a parser configured to avoid loading network resources and external entities for untrusted documents. Do not enable recovery merely to suppress syntax errors in a data export.

The example below declares a namespace mapping and selects book elements through an explicit XPath. The prefix used in the XPath is your local query alias; it does not need to match the prefix chosen by the source document. The namespace URI is the actual identity. That makes the query robust against harmless prefix spelling changes.

XPath-based Extraction

An XPath is a schema assumption. A query selecting catalog book children will not automatically find records inside a different envelope. If a supplier changes the wrapper or namespace URI, an empty result may indicate a broken contract. Compare selected counts with expected counts and raise an error when a normally populated feed suddenly contains no matching records.

Code Example

Use lxml 5.3.0 and the namespaced fixture included with this example. The output keeps the same business columns as the standard library script. Keeping those outputs identical makes it easier to compare implementations and catch differences caused by namespace handling rather than by unrelated formatting choices.

Complete input XML

<catalog xmlns="urn:catalog"><book id="0001"><title>Tea, &quot;雪&quot;</title><price>12.50</price></book><book id="0002"><title>Café</title></book></catalog>

Complete Python script

import csv
import sys
from lxml import etree as ET

def main():
    source = sys.argv[1] if len(sys.argv) > 1 else "namespaced.xml"
    destination = sys.argv[2] if len(sys.argv) > 2 else "output.csv"
    try:
        parser = ET.XMLParser(resolve_entities=False, no_network=True, load_dtd=False)
        root = ET.parse(source, parser).getroot()
        namespaces = {"c": "urn: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.xpath("/c:catalog/c:book", namespaces=namespaces):
                writer.writerow([book.get("id", ""),
                                 book.findtext("c:title", default="", namespaces=namespaces),
                                 book.findtext("c:price", default="", namespaces=namespaces)])
    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 -m pip install lxml==5.3.0
python convert-lxml.py

Expected CSV output

book_@id,book_title,book_price
0001,"Tea, ""雪""",12.50
0002,Café,

For untrusted input, review parser resource limits as well as entity settings. Large text nodes, deeply nested structures, and huge expansion results can exhaust memory even without an external entity attack. A browser or server converter should enforce explicit limits. A local script should likewise document the expected input size and refuse unexpected workloads when appropriate.

Handling Common Challenges

Nested Elements

Flattening a hierarchy requires a row definition. If each order contains several items, one row per item often works well: copy order identifiers into each item row. If an order also contains an independent repeated tag collection, decide whether to create a Cartesian product or separate output tables. Index alignment is not a safe default unless the schema explicitly defines corresponding positions.

Field names should encode enough ancestry to remain understandable. Different paths can produce the same underscore spelling, so retain structured paths internally and resolve display collisions before exporting. The browser nested XML converter handles this distinction for interactive work. In a schema-specific script, an explicit list of unique column names is usually simplest.

Namespaces

ElementTree commonly represents a namespaced tag as an expanded name containing its URI. Use a namespace map with find or findall instead of stripping namespaces from every tag. Removing them can collapse genuinely different element types into the same name. Test with a default namespace, a prefixed element namespace, and a prefixed attribute namespace if your sources use those patterns.

Whitespace is another schema decision. The examples preserve text values rather than applying trim indiscriminately. Leading spaces may matter in a code or fixed-width value. Mixed content can interleave text and elements, so reading only element.text does not reproduce the complete markup. Choose a serialization approach when the markup itself must remain inside a CSV cell.

Large Files with iterparse

Incremental parsing processes end events and writes each completed business record immediately. Clear the element after extraction, and remove completed records from their parent when possible. Clearing only text while retaining thousands of empty element objects can still grow memory. Keep the source schema and record depth explicit so you do not clear a child before its enclosing record is written.

Complete input XML

<catalog><book id="0001"><title>Tea, &quot;雪&quot;</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:
        events = ET.iterparse(source, events=("start", "end"))
        _, root = next(events)
        with open(destination, "w", encoding="utf-8-sig", newline="") as output:
            writer = csv.writer(output)
            writer.writerow(["book_@id", "book_title", "book_price"])
            depth = 1
            for event, book in events:
                if event == "start":
                    depth += 1
                    continue
                if depth == 2 and book.tag == "book":
                    writer.writerow([book.get("id", ""),
                                     book.findtext("title", default=""),
                                     book.findtext("price", default="")])
                    book.clear()
                    root.remove(book)
                depth -= 1
    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 iterparse.py

Expected CSV output

book_@id,book_title,book_price
0001,"Tea, ""雪""",12.50
0002,Café,

The incremental example does not collect every row in a list. It still needs enough memory for the current record and parser state, so an exceptionally large single record can be costly. Splitting a file at arbitrary byte offsets is unsafe because XML tags, entities, and multibyte characters can cross the boundary. Split using a schema-aware parser instead.

Best Practices

Validate with representative fixtures before scheduling a job. Include a comma, double quote, newline, Unicode character, absent element, empty element, and attribute. Parse the generated CSV with csv.reader and compare values to expected strings. A raw string comparison is also useful for a fixed byte contract, but it should not replace checking the meaning of each cell.

Keep error handling outside the main extraction loop so failures stop the job cleanly. Log counts and a fixed error category, not confidential source rows. Use a temporary output path, close the file, and atomically replace the destination after success. Keep a copy of the schema assumptions in your repository so another maintainer knows why each field was chosen.

Measure memory and elapsed time using a realistic file. Faster parsing is not helpful if repeated groups generate an unexpectedly large CSV. Enforce row and output byte limits where the downstream process has capacity constraints. Recheck those limits after adding new columns, especially when escaping quotes or adding formula protection changes the encoded output size.

When to Use an Online Tool Instead

A script is valuable for automation, but setup and maintenance are unnecessary for many occasional tasks. If you need to inspect a file, choose columns, and download a spreadsheet once, use the free XML to CSV tool. Its preview makes the row model visible, and local browser processing avoids transferring the source to a conversion server.

Related Guides