Loading XML to Python Converter...
Please wait a moment

How to Convert XML to Python Classes - Step by Step Guide

Step 1

Input Your XML Schema

Start by adding your XML data that needs to be converted to Python classes. The tool analyzes the structure to generate appropriate dataclasses.

Example: Try This XML Data

Copy and paste this XML example to see how it works:

<?xml version="1.0" encoding="UTF-8"?>
<library>
  <book id="1">
    <title>The Python Guide</title>
    <author>Elena Rodriguez</author>
    <year>2023</year>
    <price currency="USD">29.99</price>
    <available>true</available>
    <tags>
      <tag>programming</tag>
      <tag>python</tag>
    </tags>
  </book>
</library>
Step 2

Check the Generated Types

There is nothing to configure. The converter reads every copy of every element and picks the narrowest type that fits all of them, then writes Python dataclasses around those types.

•
Numbers: whole numbers become int at any length, decimals become float; 00501 or 0x1F stay str so nothing is lost
•
Repeats: an element seen more than once under a parent becomes a List, with fields merged from every copy
•
Nesting: elements with attributes or children get their own class; plain text elements become str, int, float or bool fields
•
Loading: every class gets a from_xml method built on ElementTree, so no extra packages are needed
Step 3

Get Generated Python Code

The output panel fills in as you type. Each class is a plain dataclass with a from_xml method that knows which attribute or child element each field comes from.

Python Code Output

Two of the classes generated for the example above (the full file also has the imports, a few helper functions, and the Root and Tags classes):

@dataclass
class Book:
    id: Optional[int] = None  # attribute id
    title: Optional[str] = None  # element <title>
    author: Optional[str] = None  # element <author>
    year: Optional[int] = None  # element <year>
    price: Optional[Price] = None  # element <price>
    available: Optional[bool] = None  # element <available>
    tags: Optional[Tags] = None  # element <tags>

    @classmethod
    def from_xml(cls, xml_element: ET.Element) -> Book:
        instance = cls()
        instance.id = _to_int(xml_element.get("id"))
        for child in _children(xml_element, "title")[:1]:
            instance.title = _own_text(child)
        for child in _children(xml_element, "author")[:1]:
            instance.author = _own_text(child)
        for child in _children(xml_element, "year")[:1]:
            instance.year = _to_int(_own_text(child))
        for child in _children(xml_element, "price")[:1]:
            instance.price = Price.from_xml(child)
        for child in _children(xml_element, "available")[:1]:
            instance.available = _to_bool(_own_text(child))
        for child in _children(xml_element, "tags")[:1]:
            instance.tags = Tags.from_xml(child)
        return instance


@dataclass
class Price:
    currency: Optional[str] = None  # attribute currency
    value: Optional[float] = None  # text content

    @classmethod
    def from_xml(cls, xml_element: ET.Element) -> Price:
        instance = cls()
        instance.currency = xml_element.get("currency")
        instance.value = _to_float(_own_text(xml_element))
        return instance
Step 4

Copy or Download Python Code

Perfect! Now you can use your Python classes in your applications for XML processing.

•
Copy to clipboard for immediate use in your Python projects
•
Download .py file for integration into your codebase
•
Use with frameworks like FastAPI and Django
•
Data processing and XML parsing workflows

What is XML to Python Conversion?

XML to Python conversion transforms XML schemas into Python dataclasses with proper type annotations. It reads a sample document, works out which elements nest, repeat or hold numbers, and writes classes that load documents of the same shape into typed Python objects.

Instead of walking an ElementTree by hand and calling int() on every value, you get attribute access like data.book.price.value, with type hints your editor can autocomplete. Type hints are not checked at runtime, so the classes describe your data rather than validate it.

Frequently Asked Questions

What goes into the generated Python file?

One @dataclass per XML element that has attributes or child elements, with Optional and List type hints, plus a from_xml classmethod on each class that reads an ElementTree element into it. A few small helper functions at the top turn element text into int, float or bool. The file only reads XML; it doesn't write objects back out as XML.

How does it decide between int, float, bool and str?

It looks at the text of every copy of an element or attribute, not just the first one. Whole numbers become int, and because Python ints have no size limit a 19-digit ID like 8901240544102066246 keeps every digit. Decimals become float, true/false become bool, and anything else stays str, including values with leading zeros such as 00501, hex like 0x1F, and elements that are empty in some copies. If one copy holds 42 and another holds abc, the field is str.

What happens with repeated elements, attributes and namespaces?

An element that appears more than once under the same parent becomes a List, and fields from every copy are merged, so a child that only shows up in the third <item> still gets a field. An element that appears only once in your sample is typed as a single value, so paste a sample with at least two copies if it can repeat. Elements with the same name share one class. Attributes become fields next to the child elements, text inside an element with attributes goes into a value field, and namespaced names are looked up the way ElementTree reports them, as {namespace-uri}name.

What if an XML name is not a valid Python name?

Names are turned into snake_case for fields and PascalCase for classes. Python keywords get a trailing underscore (class becomes class_), names that start with a digit get a prefix, and two names that end up the same get _2 added. The original XML name is kept in the comment next to each field and in the from_xml lookups, so the data is still read from the right place.

Which Python versions can run the generated code?

Python 3.7 or newer. The file uses dataclasses and starts with from __future__ import annotations so classes can refer to each other in any order. It only imports from the standard library: dataclasses, typing and xml.etree.ElementTree.

Can I use the classes with FastAPI or Django?

FastAPI accepts standard dataclasses as request and response bodies, so the classes can be used there once you have loaded them with from_xml. Django REST framework has no built-in support for dataclasses; you would write a serializer for them or use a package such as djangorestframework-dataclasses.

Is my XML uploaded anywhere, and is there a size limit?

No. The conversion runs in your browser and the XML never leaves your machine. There is no set limit; a document of a couple of thousand lines converts almost instantly, and very large files are limited only by your device's memory and the editor's speed.