xsd

package module
v0.0.27 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 21 Imported by: 0

README

XSD 1.0 Validator for Go

XSD 1.0 validation for Go with io/fs schema loading and streaming XML validation.

Install

go get github.com/jacoelho/xsd

Quickstart (in-memory schema)

package main

import (
    "fmt"
    "strings"
    "testing/fstest"

    "github.com/jacoelho/xsd"
    "github.com/jacoelho/xsd/errors"
)

func main() {
    schemaXML := `<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://example.com/simple"
           elementFormDefault="qualified">
  <xs:element name="person">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="age" type="xs:integer"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>`

    fsys := fstest.MapFS{
        "simple.xsd": &fstest.MapFile{Data: []byte(schemaXML)},
    }

    schema, err := xsd.LoadWithOptions(fsys, "simple.xsd", xsd.NewLoadOptions())
    if err != nil {
        fmt.Printf("Load schema: %v\n", err)
        return
    }

    xmlDoc := `<?xml version="1.0"?>
<person xmlns="http://example.com/simple">
  <name>John Doe</name>
  <age>30</age>
</person>`

    if err := schema.Validate(strings.NewReader(xmlDoc)); err != nil {
        if violations, ok := errors.AsValidations(err); ok {
            for _, v := range violations {
                fmt.Println(v.Error())
            }
            return
        }
        fmt.Printf("Validate: %v\n", err)
        return
    }

    fmt.Println("Document is valid")
}

SchemaSet API

set := xsd.NewSchemaSet(xsd.NewLoadOptions())
if err := set.AddFS(fsys, "schema-a.xsd"); err != nil {
    // handle
}
if err := set.AddFS(fsys, "schema-b.xsd"); err != nil {
    // handle
}
schema, err := set.Compile()
if err != nil {
    // handle
}
if err := schema.Validate(strings.NewReader(xmlDoc)); err != nil {
    // handle
}

This snippet assumes fsys and xmlDoc are defined as in Quickstart. SchemaSet compiles all added roots into one runtime schema.

Validate from files

package main

import (
    "fmt"

    "github.com/jacoelho/xsd"
    "github.com/jacoelho/xsd/errors"
)

func main() {
    schema, err := xsd.LoadFile("schema.xsd")
    if err != nil {
        fmt.Printf("Load schema: %v\n", err)
        return
    }

    if err := schema.ValidateFile("document.xml"); err != nil {
        if violations, ok := errors.AsValidations(err); ok {
            for _, v := range violations {
                fmt.Println(v.Error())
            }
            return
        }
        fmt.Printf("Validate: %v\n", err)
        return
    }

    fmt.Println("Document is valid")
}

To validate from any fs.FS:

if err := schema.ValidateFSFile(fsys, "document.xml"); err != nil {
    // handle
}

Load options

opts := xsd.NewLoadOptions().
    WithAllowMissingImportLocations(true).
    WithRuntimeOptions(
        xsd.NewRuntimeOptions().
            WithMaxDFAStates(4096).
            WithMaxOccursLimit(1_000_000),
    )

schema, err := xsd.LoadWithOptions(fsys, "schema.xsd", opts)

Options:

  • WithAllowMissingImportLocations: when true, imports without schemaLocation are skipped. Missing import files are also skipped when the filesystem returns fs.ErrNotExist.
  • WithRuntimeOptions: applies runtime compilation/validation limits from RuntimeOptions.
  • WithSchemaMaxDepth / WithSchemaMaxAttrs / WithSchemaMaxTokenSize / WithSchemaMaxQNameInternEntries: schema parser XML limits.
  • instance limits (WithInstanceMaxDepth, WithInstanceMaxAttrs, WithInstanceMaxTokenSize, WithInstanceMaxQNameInternEntries) are set on RuntimeOptions.

Compile with Runtime Options

set := xsd.NewSchemaSet(xsd.NewLoadOptions())
if err := set.AddFS(fsys, "schema.xsd"); err != nil {
    // handle
}

schemaA, err := set.Compile()
if err != nil {
    // handle
}

runtimeOpts := xsd.NewRuntimeOptions().
    WithMaxDFAStates(2048).
    WithInstanceMaxDepth(512)
schemaB, err := set.CompileWithRuntimeOptions(runtimeOpts)
if err != nil {
    // handle
}

Loading behavior

  • LoadWithOptions accepts any fs.FS; include/import locations resolve relative to the including schema path.
  • Includes MUST resolve successfully.
  • Imports without schemaLocation are rejected unless WithAllowMissingImportLocations(true) is set.

Validation behavior

  • Schema.Validate is safe for concurrent use.
  • Validation is streaming; the document is not loaded into a DOM.
  • Instance-document schema hints (xsi:schemaLocation, xsi:noNamespaceSchemaLocation) are ignored.

Error handling

Schema.Validate returns errors.ValidationList for validation failures, XML parsing failures, and validation calls made without a loaded schema. Schema.ValidateFile can return file I/O errors before validation starts.

Each errors.Validation includes:

  • Code (W3C codes like cvc-elt.1, or local codes like xsd-schema-not-loaded)
  • Message
  • Path (best-effort instance path)
  • Line and Column when available
  • Expected and Actual when available

Constraints and limits

  • XSD 1.0 only.
  • No HTTP imports.
  • Regex patterns must be compatible with Go's regexp.
  • xs:redefine is not supported.
  • DateTime parsing uses time.Parse (years 0001-9999; no year 0, BCE, or >9999).
  • DTDs and external entity resolution are not supported.
  • Instance documents must be UTF-8.

CLI (xmllint)

make xmllint
./bin/xmllint --schema schema.xsd document.xml

Options:

  • --schema (required): path to the XSD schema file
  • --cpuprofile: write a CPU profile to a file
  • --memprofile: write a heap profile to a file

Testing

go test -timeout 60s ./...
make w3c

Architecture

See docs/architecture.md.

License

MIT

Documentation

Overview

Package xsd provides XSD 1.0 schema loading and XML validation backed by io/fs.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LoadOptions added in v0.0.16

type LoadOptions struct {
	// contains filtered or unexported fields
}

LoadOptions configures schema loading and default runtime compilation.

func NewLoadOptions added in v0.0.23

func NewLoadOptions() LoadOptions

NewLoadOptions returns a default, valid load options value.

func (LoadOptions) RuntimeOptions added in v0.0.23

func (o LoadOptions) RuntimeOptions() RuntimeOptions

RuntimeOptions returns the runtime options embedded in the load options.

func (LoadOptions) Validate added in v0.0.23

func (o LoadOptions) Validate() error

Validate validates load options values.

func (LoadOptions) WithAllowMissingImportLocations added in v0.0.23

func (o LoadOptions) WithAllowMissingImportLocations(value bool) LoadOptions

WithAllowMissingImportLocations controls whether imports without schemaLocation are skipped.

func (LoadOptions) WithRuntimeOptions added in v0.0.23

func (o LoadOptions) WithRuntimeOptions(value RuntimeOptions) LoadOptions

WithRuntimeOptions sets all runtime options in one call.

func (LoadOptions) WithSchemaMaxAttrs added in v0.0.23

func (o LoadOptions) WithSchemaMaxAttrs(value int) LoadOptions

WithSchemaMaxAttrs sets the schema XML max attributes limit (0 uses default).

func (LoadOptions) WithSchemaMaxDepth added in v0.0.23

func (o LoadOptions) WithSchemaMaxDepth(value int) LoadOptions

WithSchemaMaxDepth sets the schema XML max depth limit (0 uses default).

func (LoadOptions) WithSchemaMaxQNameInternEntries added in v0.0.23

func (o LoadOptions) WithSchemaMaxQNameInternEntries(value int) LoadOptions

WithSchemaMaxQNameInternEntries sets the schema QName interning cache size (0 leaves xmlstream default).

func (LoadOptions) WithSchemaMaxTokenSize added in v0.0.23

func (o LoadOptions) WithSchemaMaxTokenSize(value int) LoadOptions

WithSchemaMaxTokenSize sets the schema XML max token size limit (0 uses default).

type QName added in v0.0.23

type QName = qname.QName

QName is a public qualified name with namespace and local part.

type RuntimeOptions added in v0.0.23

type RuntimeOptions struct {
	// contains filtered or unexported fields
}

RuntimeOptions configures runtime compilation and instance XML limits.

func NewRuntimeOptions added in v0.0.23

func NewRuntimeOptions() RuntimeOptions

NewRuntimeOptions returns a default, valid runtime options value.

func (RuntimeOptions) Validate added in v0.0.23

func (o RuntimeOptions) Validate() error

Validate validates runtime options values.

func (RuntimeOptions) WithInstanceMaxAttrs added in v0.0.23

func (o RuntimeOptions) WithInstanceMaxAttrs(value int) RuntimeOptions

WithInstanceMaxAttrs sets the instance XML max attributes limit (0 uses default).

func (RuntimeOptions) WithInstanceMaxDepth added in v0.0.23

func (o RuntimeOptions) WithInstanceMaxDepth(value int) RuntimeOptions

WithInstanceMaxDepth sets the instance XML max depth limit (0 uses default).

func (RuntimeOptions) WithInstanceMaxQNameInternEntries added in v0.0.23

func (o RuntimeOptions) WithInstanceMaxQNameInternEntries(value int) RuntimeOptions

WithInstanceMaxQNameInternEntries sets the instance QName interning cache size (0 leaves xmlstream default).

func (RuntimeOptions) WithInstanceMaxTokenSize added in v0.0.23

func (o RuntimeOptions) WithInstanceMaxTokenSize(value int) RuntimeOptions

WithInstanceMaxTokenSize sets the instance XML max token size limit (0 uses default).

func (RuntimeOptions) WithMaxDFAStates added in v0.0.23

func (o RuntimeOptions) WithMaxDFAStates(value uint32) RuntimeOptions

WithMaxDFAStates sets the runtime DFA state limit (0 uses default).

func (RuntimeOptions) WithMaxOccursLimit added in v0.0.23

func (o RuntimeOptions) WithMaxOccursLimit(value uint32) RuntimeOptions

WithMaxOccursLimit sets the runtime maxOccurs compilation limit (0 uses default).

type Schema

type Schema struct {
	// contains filtered or unexported fields
}

Schema wraps a compiled schema with convenience methods.

func LoadFile

func LoadFile(path string) (*Schema, error)

LoadFile loads and compiles a schema from a file path.

func LoadWithOptions added in v0.0.16

func LoadWithOptions(fsys fs.FS, location string, opts LoadOptions) (*Schema, error)

LoadWithOptions loads and compiles a schema with explicit configuration.

Example
package main

import (
	"fmt"
	"testing/fstest"

	"github.com/jacoelho/xsd"
)

func main() {
	schemaXML := `<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://example.com/simple"
           elementFormDefault="qualified">
  <xs:element name="message" type="xs:string"/>
</xs:schema>`

	fsys := fstest.MapFS{
		"simple.xsd": &fstest.MapFile{Data: []byte(schemaXML)},
	}

	loaded, err := xsd.LoadWithOptions(fsys, "simple.xsd", xsd.NewLoadOptions())
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	if loaded == nil {
		fmt.Println("Error: schema is nil")
		return
	}
	fmt.Println("Schema loaded successfully")
}
Output:

Schema loaded successfully

func (*Schema) Validate

func (s *Schema) Validate(r io.Reader) error

Validate validates a document against the schema.

Example
package main

import (
	"fmt"
	"strings"
	"testing/fstest"

	"github.com/jacoelho/xsd"
	"github.com/jacoelho/xsd/errors"
)

func main() {
	schemaXML := `<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://example.com/simple"
           elementFormDefault="qualified">
  <xs:element name="person">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="age" type="xs:integer"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>`

	fsys := fstest.MapFS{
		"simple.xsd": &fstest.MapFile{Data: []byte(schemaXML)},
	}

	schema, err := xsd.LoadWithOptions(fsys, "simple.xsd", xsd.NewLoadOptions())
	if err != nil {
		fmt.Printf("Error loading schema: %v\n", err)
		return
	}

	xmlDoc := `<?xml version="1.0"?>
<person xmlns="http://example.com/simple">
  <name>John Doe</name>
  <age>30</age>
</person>`

	if err := schema.Validate(strings.NewReader(xmlDoc)); err != nil {
		if violations, ok := errors.AsValidations(err); ok {
			for _, v := range violations {
				fmt.Printf("Validation: %s\n", v.Error())
			}
			return
		}
		fmt.Printf("Error: %v\n", err)
		return
	}
	fmt.Println("Document is valid")
}
Output:

Document is valid

func (*Schema) ValidateFSFile added in v0.0.24

func (s *Schema) ValidateFSFile(fsys fs.FS, path string) (err error)

ValidateFSFile validates an XML file from the provided filesystem.

func (*Schema) ValidateFile

func (s *Schema) ValidateFile(path string) (err error)

ValidateFile validates an XML file against the schema.

type SchemaSet added in v0.0.25

type SchemaSet struct {
	// contains filtered or unexported fields
}

SchemaSet owns schema sources and compiles them into a runtime schema.

func NewSchemaSet added in v0.0.25

func NewSchemaSet(opts ...LoadOptions) *SchemaSet

NewSchemaSet creates an empty schema set.

func (*SchemaSet) AddFS added in v0.0.25

func (s *SchemaSet) AddFS(fsys fs.FS, location string) error

AddFS adds one schema root location from fsys.

func (*SchemaSet) Compile added in v0.0.25

func (s *SchemaSet) Compile() (*Schema, error)

Compile compiles all added schema roots using set load options.

func (*SchemaSet) CompileWithRuntimeOptions added in v0.0.25

func (s *SchemaSet) CompileWithRuntimeOptions(opts RuntimeOptions) (*Schema, error)

CompileWithRuntimeOptions compiles all added roots with explicit runtime options.

func (*SchemaSet) WithLoadOptions added in v0.0.25

func (s *SchemaSet) WithLoadOptions(opts LoadOptions) *SchemaSet

WithLoadOptions replaces schema-set load options.

Directories

Path Synopsis
cmd
xmllint command
Command xmllint validates XML documents against XSD schemas.
Command xmllint validates XML documents against XSD schemas.
Package errors defines validation errors and W3C XSD error codes.
Package errors defines validation errors and W3C XSD error codes.
internal
analysis
Package analysis derives deterministic semantic indexes from validated schemas.
Package analysis derives deterministic semantic indexes from validated schemas.
attrgroupwalk
Package attrgroupwalk traverses attribute-group references with cycle handling.
Package attrgroupwalk traverses attribute-group references with cycle handling.
attrwildcard
Package attrwildcard collects and composes attribute wildcard constraints.
Package attrwildcard collects and composes attribute wildcard constraints.
builtins
Package builtins exposes builtin XSD type registry and names.
Package builtins exposes builtin XSD type registry and names.
compiler
Package compiler orchestrates semantic normalization and runtime compilation.
Package compiler orchestrates semantic normalization and runtime compilation.
complextypeplan
Package complextypeplan builds normalized complex-type compilation plans.
Package complextypeplan builds normalized complex-type compilation plans.
contentmodel
Package contentmodel compiles content model particles into Glushkov structures.
Package contentmodel compiles content model particles into Glushkov structures.
diag
Package diag collects and sorts diagnostics emitted during schema processing.
Package diag collects and sorts diagnostics emitted during schema processing.
durationconv
Package durationconv converts XSD durations to comparable runtime forms.
Package durationconv converts XSD durations to comparable runtime forms.
durationlex
Package durationlex compares and normalizes lexical XSD duration values.
Package durationlex compares and normalizes lexical XSD duration values.
facetrules
Package facetrules validates cross-facet consistency rules.
Package facetrules validates cross-facet consistency rules.
facets
Package facets provides shared helpers for facet validation and comparison.
Package facets provides shared helpers for facet validation and comparison.
facetvalue
Package facetvalue exposes facet and comparable-value operations.
Package facetvalue exposes facet and comparable-value operations.
fieldresolve
Package fieldresolve resolves identity-constraint field paths to declarations.
Package fieldresolve resolves identity-constraint field paths to declarations.
globaldecl
Package globaldecl dispatches schema global declarations by kind.
Package globaldecl dispatches schema global declarations by kind.
graphcycle
Package graphcycle detects cycles in directed schema dependency graphs.
Package graphcycle detects cycles in directed schema dependency graphs.
grouprefs
Package grouprefs expands and validates model-group references.
Package grouprefs expands and validates model-group references.
identity
Package identity evaluates identity-constraint rows and conflicts.
Package identity evaluates identity-constraint rows and conflicts.
identitypath
Package identitypath compiles selector and field XPath-like identity paths.
Package identitypath compiles selector and field XPath-like identity paths.
ids
Package ids defines shared typed identifiers for compiled schema artifacts.
Package ids defines shared typed identifiers for compiled schema artifacts.
loadguard
Package loadguard tracks load state to detect circular schema loading.
Package loadguard tracks load state to detect circular schema loading.
loadmerge
Package loadmerge merges parsed schemas with origin-aware duplicate checks.
Package loadmerge merges parsed schemas with origin-aware duplicate checks.
model
Package model defines the XSD schema model and shared type-system structures.
Package model defines the XSD schema model and shared type-system structures.
normalize
Package normalize resolves and validates parsed schema components.
Package normalize resolves and validates parsed schema components.
num
Package num provides XSD numeric parsing and comparison helpers.
Package num provides XSD numeric parsing and comparison helpers.
objects
Package objects exposes schema object graph declarations.
Package objects exposes schema object graph declarations.
occurs
Package occurs models XSD occurrence bounds and arithmetic.
Package occurs models XSD occurrence bounds and arithmetic.
occurspolicy
Package occurspolicy validates occurrence constraints and all-group bounds.
Package occurspolicy validates occurrence constraints and all-group bounds.
parser
Package parser parses XSD documents into raw symbolic components.
Package parser parses XSD documents into raw symbolic components.
prep
Package prep runs semantic preparation checks before runtime compilation.
Package prep runs semantic preparation checks before runtime compilation.
preprocessor
Package preprocessor loads schema documents and resolves include/import directives.
Package preprocessor loads schema documents and resolves include/import directives.
qname
Package qname provides deterministic QName ordering helpers.
Package qname provides deterministic QName ordering helpers.
resolveguard
Package resolveguard tracks resolution state to detect reference cycles.
Package resolveguard tracks resolution state to detect reference cycles.
runtime
Package runtime holds immutable runtime tables produced by exp compilation.
Package runtime holds immutable runtime tables produced by exp compilation.
runtimeassemble
Package runtimeassemble compiles normalized schema artifacts into runtime tables.
Package runtimeassemble compiles normalized schema artifacts into runtime tables.
runtimeids
Package runtimeids assigns stable runtime identifiers to compiled components.
Package runtimeids assigns stable runtime identifiers to compiled components.
semanticcheck
Package semanticcheck validates schema structure rules before compilation.
Package semanticcheck validates schema structure rules before compilation.
semanticresolve
Package semanticresolve resolves QName references in parsed schemas.
Package semanticresolve resolves QName references in parsed schemas.
set
Package set provides schema-set orchestration for schema loading and delegates semantic/runtime compilation to internal/compiler.
Package set provides schema-set orchestration for schema loading and delegates semantic/runtime compilation to internal/compiler.
stack
Package stack provides reusable stack helpers for validation/runtime state.
Package stack provides reusable stack helpers for validation/runtime state.
substpolicy
Package substpolicy checks substitution-group compatibility rules.
Package substpolicy checks substitution-group compatibility rules.
traversal
Package traversal walks schema structures for analysis and compilation.
Package traversal walks schema structures for analysis and compilation.
typechain
Package typechain computes type-derivation ancestry and relationships.
Package typechain computes type-derivation ancestry and relationships.
typeresolve
Package typeresolve provides shared pure helpers for schema type operations.
Package typeresolve provides shared pure helpers for schema type operations.
types
Package types exposes schema type-system contracts and aliases.
Package types exposes schema type-system contracts and aliases.
typewalk
Package typewalk traverses type references in schema definitions.
Package typewalk traverses type references in schema definitions.
validationengine
Package validationengine exposes the validation engine and session entrypoints over compiled schema information.
Package validationengine exposes the validation engine and session entrypoints over compiled schema information.
validator
Package validator validates XML documents against compiled XSD schemas.
Package validator validates XML documents against compiled XSD schemas.
validatorgen
Package validatorgen compiles validator functions from resolved schemas.
Package validatorgen compiles validator functions from resolved schemas.
value
Package value parses and normalizes XSD lexical value forms.
Package value parses and normalizes XSD lexical value forms.
value/datetime
Package datetime parses and normalizes XSD date/time lexical values.
Package datetime parses and normalizes XSD date/time lexical values.
value/temporal
Package temporal represents normalized temporal values used by validators.
Package temporal represents normalized temporal values used by validators.
valuecodec
Package valuecodec encodes and decodes typed value representations.
Package valuecodec encodes and decodes typed value representations.
valueparse
Package valueparse parses lexical inputs into typed value variants.
Package valueparse parses lexical inputs into typed value variants.
values
Package values exposes lexical, canonical, and value-key helpers.
Package values exposes lexical, canonical, and value-key helpers.
valuesemantics
Package valuesemantics compares typed values using XSD value-space rules.
Package valuesemantics compares typed values using XSD value-space rules.
valuevalidate
Package valuevalidate validates default and fixed values against types.
Package valuevalidate validates default and fixed values against types.
whitespace
Package whitespace applies XSD whiteSpace normalization rules.
Package whitespace applies XSD whiteSpace normalization rules.
wildcardpolicy
Package wildcardpolicy evaluates wildcard namespace and processContents rules.
Package wildcardpolicy evaluates wildcard namespace and processContents rules.
xiter
Package xiter provides small iterator helpers used across the compiler.
Package xiter provides small iterator helpers used across the compiler.
xmllex
Package xmllex provides lexical XML parsing helpers.
Package xmllex provides lexical XML parsing helpers.
xmlnames
Package xmlnames defines shared XML namespace and prefix constants.
Package xmlnames defines shared XML namespace and prefix constants.
xmltree
Package xmltree provides a minimal DOM abstraction and XML parsing.
Package xmltree provides a minimal DOM abstraction and XML parsing.
xpath
Package xpath provides a small compiler for the restricted XPath subset used by XSD identity constraints.
Package xpath provides a small compiler for the restricted XPath subset used by XSD identity constraints.
pkg
xmlstream
Package xmlstream provides a namespace-aware streaming XML reader built on xmltext.
Package xmlstream provides a namespace-aware streaming XML reader built on xmltext.
xmltext
Package xmltext provides a streaming XML 1.0 tokenizer that returns caller-owned bytes and avoids building a DOM.
Package xmltext provides a streaming XML 1.0 tokenizer that returns caller-owned bytes and avoids building a DOM.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL