XML to Python Converter

Convert an XML sample into Python dataclasses, TypedDicts, Pydantic models, or a ready to paste dictionary literal.

XML
Python
Runs locally in your browser

About the XML to Python Converter

Python has several reasonable ways to model an XML payload and the right one depends on what you are building. A quick script often wants nothing more than a dictionary literal it can iterate over. A library wants dataclasses so callers get attribute access and a helpful repr. A typed codebase wants TypedDicts so the values keep their dict shape while mypy still checks the keys. A validating API layer wants Pydantic models. This page produces all four from the same input.

Field names are converted to snake case, which is where most hand written models go wrong: a dewPoint element becomes dew_point and a hyphenated tag becomes an underscore name, both of which are legal Python identifiers. Types come from the values in your sample, so digits give int, decimals give float, true and false give bool, and an empty element gives Optional[Any] since nothing indicates its real type.

Class definitions are emitted in dependency order, innermost first, so the file runs top to bottom without a forward reference problem. The dict literal option is different in kind: it renders your actual sample data as Python, complete with True, False and None instead of their JSON spellings, which makes it ideal for pinning a fixture into a test. For the same job starting from a config file, see YAML to Python.

How to use

  1. Paste the XML payload you want a Python model for.
  2. Choose what to generate: dataclasses, TypedDicts, Pydantic models or a dict literal.
  3. Rename the root type if the root element name is not what you want the class called.
  4. Copy the code or download it as a .py file.

Common questions

Why is the last class printed first?
Nested classes must be defined before the class that refers to them, so the output is ordered innermost first and runs without forward references.
Does the dict option include my data?
Yes. That mode prints the parsed sample as a Python literal, which makes it a quick way to build a test fixture.
Are the dataclasses ready for XML parsing?
They describe the shape only. You still need a parser such as ElementTree or lxml to fill them from a document.
How are attribute names kept apart from elements?
Pick a prefix in the toolbar. With None selected an attribute and a child element sharing a name would collide.