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 guessesxs:integer. If it containstrue, it guessesxs: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
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
100% client-side. Nothing uploaded.
How do you usually handle XML validation in your projects? Let me know in the comments.
Top comments (0)