jsonecho

XML to Python

Paste an XML document and get Python types that match its structure.

Loading the tool...

How to use XML to Python

  1. Paste a representative XML sample, ideally one with all the optional fields filled in.
  2. Set the name of the root type, and decide whether you want helper code as well or types only.
  3. Copy the generated Python code into your project.

About XML to Python

Writing model classes by hand for a big XML payload is dull, and it is where typos creep in. Paste a sample here and the generator works out the structure: which fields exist, which are objects, which are arrays and what type each value has. The output is dataclasses with type hints, plus from_dict and to_dict helpers.

XML is first converted to JSON the same way as in our XML to JSON tool: attributes get an @_ prefix and text content next to attributes is called #text. The Python types are generated from that result. Field names that are not valid Python identifiers are converted, and the original name is kept for serialization.

Using the generated code

Call Root.from_dict(json.loads(text)) to get an object, and to_dict() to go back.

Optional fields use Optional[T] from the typing module and default to None.

Frequently asked questions

What does the generated Python code depend on?

The output is dataclasses with type hints, plus from_dict and to_dict helpers.

How do I parse XML with the result?

Convert the XML to JSON first (our XML to JSON tool does this the same way), then call Root.from_dict(json.loads(text)) to get an object, and to_dict() to go back.

How are optional and missing fields handled?

Optional fields use Optional[T] from the typing module and default to None.

Does the generator look at more than one record?

It only knows what is in your sample. If a field is missing from your example, it will not appear in the types, and if a value is null in your example, its type is unknown. Paste an example in which as many fields as possible are filled in, or paste an array with several different records.

Is my XML sent to a server?

No. The generator is downloaded to your browser the first time you use it, about 1 MB, and everything runs locally.

More in Data to Class

All tools →