DEV Community

Cover image for How to Generate an XSD Schema from an XML File
kandz
kandz

Posted on Originally published at tools.kandz.me

How to Generate an XSD Schema from an XML File

Writing an XSD (XML Schema Definition) by hand is tedious.

You have to look at an XML sample and manually define every element, attribute, and data type. One typo and the validation fails.

Generating the schema automatically from a sample file is called "schema inference." Let's look at how it works.


How Inference Works

When a tool generates a schema, it looks at your XML and makes educated guesses based on the structure and content:

  • Elements: Every tag becomes an xs:element.
  • Hierarchy: Nested tags become complex types.
  • Data Types: If a tag contains 123, it guesses xs:integer. If it contains true, it guesses xs:boolean.
  • Occurrences: If a tag appears multiple times, the tool sets maxOccurs="unbounded" to allow for arrays.

The Command-Line Way (Trang)

The most popular open-source tool for this is Trang. It's a Java-based tool that can infer an XSD from an XML file.

You can download the Trang JAR file and run it from your terminal:

java -jar trang.jar input.xml output.xsd
Enter fullscreen mode Exit fullscreen mode

This reads the XML, analyzes the structure, and outputs a basic XSD.


Common Gotchas

  • Empty Elements: If an element is empty in your sample, the tool can't guess the type and will usually default to xs:string.
  • Too Strict: Sometimes tools make the schema too strict. If a tag appears once in your sample, the tool might enforce maxOccurs="1", which will break when real data has multiple items.
  • Privacy: Uploading internal XML data to a random online tool is a security risk.

The Visual Way

If you want to automatically infer and generate W3C XML Schema Definition (XSD) documents from raw XML samples without installing Java or uploading your data to a server, I built a free XML Schema Generator.

What it does:

  • Automatically infers W3C XML Schema (XSD)
  • Generates it from raw XML samples
  • Saves hours of manual mapping

Try it here

100% client-side. Nothing uploaded.


How do you usually handle XML validation in your projects? Let me know in the comments.

Top comments (0)