xsd

package module
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2025 License: MIT Imports: 21 Imported by: 0

README

go-xsd

CI Go Report Card GoDoc codecov

A comprehensive XML Schema Definition (XSD) validator for Go that provides W3C-compliant XML validation against XSD schemas.

Features

Core Validation
  • Full XSD 1.0 Support: Comprehensive validation according to W3C XML Schema specifications
  • Schema Loading: Load schemas with automatic import/include resolution and circular dependency protection
  • Built-in Types: All standard XSD built-in types (string, int, date, etc.)
  • Complex Types: Support for sequences, choices, all groups, and nested content models
    • ComplexContent with extension/restriction
    • SimpleContent with extension/restriction
    • Mixed content models
  • Simple Types: Full support for restrictions, lists, unions, and all standard facets
  • Type Derivation: Proper type compatibility checking for extensions and restrictions
Advanced Features
  • Identity Constraints: key, keyref, and unique constraints with XPath selectors
    • Proper ID/IDREF type detection (not just name-based)
    • Type-aware validation including derived types
  • Wildcards: <xs:any> and <xs:anyAttribute> with namespace constraint validation
    • Namespace constraints: ##any, ##other, ##targetNamespace, ##local
    • ProcessContents modes: strict, lax, skip
  • Substitution Groups: Element substitution with type compatibility verification
    • Validates that substituting element's type derives from head element's type
    • Cycle detection prevents infinite recursion
  • Fixed/Default Values: Validation of fixed and default attribute/element values
  • Attribute Groups: Full support for attribute group references and resolution
  • Model Groups: Support for named group definitions and references
Performance & Safety
  • Schema Caching: Efficient schema reuse with LRU caching
  • Thread-Safe: Concurrent schema validation support with proper locking
  • Cycle Detection: Protects against infinite recursion in type hierarchies
  • Memory Efficient: Optimized allocations in hot paths, GC-friendly design

Installation

go get github.com/agentflare-ai/go-xsd

Quick Start

Basic Validation
package main

import (
    "fmt"
    "log"

    "github.com/agentflare-ai/go-xsd"
    "github.com/agentflare-ai/go-xmldom"
)

func main() {
    // Load schema
    loader := xsd.NewSchemaLoader("./schemas")
    schema, err := loader.LoadSchemaWithImports("myschema.xsd")
    if err != nil {
        log.Fatal(err)
    }

    // Parse XML document
    doc, err := xmldom.ParseFile("document.xml")
    if err != nil {
        log.Fatal(err)
    }

    // Validate
    validator := xsd.NewValidator(schema)
    violations := validator.Validate(doc)

    if len(violations) > 0 {
        for _, v := range violations {
            if v.Attribute != "" {
                fmt.Printf("[%s] Attribute '%s': %s\n", v.Code, v.Attribute, v.Message)
            } else {
                fmt.Printf("[%s] %s\n", v.Code, v.Message)
            }
        }
    } else {
        fmt.Println("Document is valid!")
    }
}
Schema Loading with Imports
loader := xsd.NewSchemaLoader("./schemas")
loader.AllowRemote = true // Enable remote schema loading (disabled by default)

schema, err := loader.LoadSchemaWithImports("schema.xsd")
if err != nil {
    log.Fatal(err)
}

// The loader automatically resolves all imports and includes
Using the Schema Cache
// Create a cache for frequently used schemas
cache := xsd.NewSchemaCache(100) // Max 100 schemas

// Load with caching
schema, err := cache.GetOrLoad("./schemas/myschema.xsd", func(path string) (*xsd.Schema, error) {
    loader := xsd.NewSchemaLoader(filepath.Dir(path))
    return loader.LoadSchemaWithImports(filepath.Base(path))
})
Advanced Example: Type-Safe Validation
// Schema with ID/IDREF constraints and substitution groups
schemaXML := `
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <!-- Base vehicle element -->
  <xs:element name="vehicle" type="VehicleType"/>

  <!-- Car can substitute for vehicle -->
  <xs:element name="car" type="CarType" substitutionGroup="vehicle"/>

  <xs:complexType name="VehicleType">
    <xs:sequence>
      <xs:element name="brand" type="xs:string"/>
    </xs:sequence>
    <xs:attribute name="id" type="xs:ID" use="required"/>
  </xs:complexType>

  <xs:complexType name="CarType">
    <xs:complexContent>
      <xs:extension base="VehicleType">
        <xs:sequence>
          <xs:element name="doors" type="xs:int"/>
        </xs:sequence>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>
</xs:schema>`

// The validator will:
// - Check that 'car' type derives from 'vehicle' type (type compatibility)
// - Validate 'id' attribute as xs:ID type (not just by name)
// - Detect duplicate ID values
// - Ensure proper type structure with extensions

API Overview

Core Types
SchemaLoader

Handles loading XSD schemas from files or URLs with automatic import/include resolution:

type SchemaLoader struct {
    BaseDir     string      // Base directory for relative paths
    AllowRemote bool        // Allow loading remote schemas
}

func NewSchemaLoader(baseDir string) *SchemaLoader
func (sl *SchemaLoader) LoadSchemaWithImports(path string) (*Schema, error)
Schema

Represents a compiled XSD schema:

type Schema struct {
    TargetNamespace    string
    ElementDecls       map[QName]*ElementDecl
    TypeDefs           map[QName]Type
    SubstitutionGroups map[QName][]QName
}
Validator

Validates XML documents against schemas:

type Validator struct {
    // Internal state
}

func NewValidator(schema *Schema) *Validator
func (v *Validator) Validate(doc xmldom.Document) []Violation
Violation

Represents a validation error:

type Violation struct {
    Element   xmldom.Element  // The violating element
    Attribute string         // Attribute name (if violation is attribute-related)
    Code      string         // W3C error code (e.g., "cvc-complex-type.2.4.d")
    Message   string         // Human-readable error message
    Expected  []string       // Expected values (for enumerations)
    Actual    string         // Actual value that failed validation
}

Error codes follow W3C XML Schema validation error conventions (cvc-* codes).

Type System

The library supports all XSD types:

  • Simple Types: string, int, boolean, date, time, decimal, etc.
  • Complex Types: Elements with child content and attributes
  • Lists: Space-separated lists of values
  • Unions: Values that can be one of several types
  • Restrictions: Types with facet constraints (minLength, maxLength, pattern, etc.)
Identity Constraints

Support for XSD identity constraints:

// Automatically validated when present in schema
<xs:key name="productKey">
    <xs:selector xpath="product"/>
    <xs:field xpath="@id"/>
</xs:key>

<xs:keyref name="orderProductRef" refer="productKey">
    <xs:selector xpath="order/item"/>
    <xs:field xpath="@productId"/>
</xs:keyref>

Advanced Features

Custom Type Validation

The library validates all standard XSD facets:

  • Length constraints: minLength, maxLength, length
  • Numeric bounds: minInclusive, maxInclusive, minExclusive, maxExclusive
  • Total digits and fraction digits
  • Pattern matching (regular expressions)
  • Enumeration restrictions
  • Whitespace handling
Substitution Groups

Elements can be substituted based on their substitution group membership:

// Schema automatically handles substitution group validation
<xs:element name="vehicle" type="VehicleType"/>
<xs:element name="car" type="CarType" substitutionGroup="vehicle"/>
<xs:element name="truck" type="TruckType" substitutionGroup="vehicle"/>
Wildcards with Namespace Processing

Support for <xs:any> elements with proper namespace constraint validation:

<xs:any namespace="##any" processContents="lax"/>
<xs:any namespace="##other" processContents="strict"/>
<xs:any namespace="http://example.com ##targetNamespace" processContents="skip"/>

Testing

Unit Tests

Run the test suite:

go test -v ./...

Run tests with coverage:

go test -v -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
W3C Conformance Tests

The library is tested against the official W3C XML Schema Test Suite:

# Auto-download and run W3C conformance tests
go run ./cmd/w3c_test --auto-download --analyze

# View detailed results
go run ./cmd/w3c_test --auto-download --verbose

CI Integration: W3C tests run automatically in CI/CD before each release to ensure standards compliance.

Test Coverage

The library includes comprehensive tests including:

  • W3C Conformance Suite: Official W3C test cases (runs in CI)
  • Identity Constraints: key, keyref, and unique validation
  • Substitution Groups: Element substitution and type checking
  • Wildcard Validation: xs:any and xs:anyAttribute handling
  • Fixed/Default Values: Attribute and element defaults
  • Union and List Types: Complex type composition

Error Codes

Validation errors use W3C XML Schema validation error codes (Component Validation Constraint codes):

Code Description
cvc-complex-type.2.4.a Missing required element
cvc-complex-type.2.4.b Element not allowed by content model
cvc-complex-type.2.4.d Unexpected element
cvc-datatype-valid.1 Invalid value for datatype
cvc-enumeration-valid Value not in enumeration
cvc-id.1 ID value must be unique
cvc-id.2 Duplicate ID value
cvc-wildcard.2 Element not allowed by namespace constraint
cvc-attribute.3 Attribute value invalid
cvc-complex-type.3.2.2 Attribute not allowed
cvc-complex-type.4 Attribute required but missing

Full list follows W3C XML Schema 1.0 Part 1: Structures specification.

Project Structure

go-xsd/
├── schema.go              # Core schema types and structures
├── schema_loader.go       # Schema loading with imports
├── schema_validator.go    # Schema-to-schema validation
├── validator.go           # Document validation engine
├── builtin_types.go       # XSD built-in type definitions
├── facets.go             # Facet validation
├── identity_constraints.go # Key/keyref/unique validation
├── wildcards.go          # Any/anyAttribute support
├── union_list_types.go   # Union and list type handling
├── fixed_default.go      # Fixed/default value validation
├── cache.go              # Schema caching with LRU
├── diagnostic.go         # Violation reporting and formatting
├── fixes.plan.md         # Development roadmap and tracking
└── cmd/
    ├── validate/         # CLI validation tool
    └── w3c_test/         # W3C test suite runner

Command-Line Tools

validate

Validate an XML document against a schema:

go run ./cmd/validate schema.xsd document.xml
w3c_test

Run W3C XSD test suite:

# Auto-download and run (downloads once, cached for 7 days)
go run ./cmd/w3c_test --auto-download

# Run with specific suite directory
go run ./cmd/w3c_test -suite /path/to/w3c/testsuite

# Force fresh download (bypasses cache)
go run ./cmd/w3c_test --force-download

# Run specific test file
go run ./cmd/w3c_test --auto-download -file msMeta/test_w3c.xml

# Generate failure analysis report
go run ./cmd/w3c_test --auto-download -analyze

Note: The test suite (≈50MB) is automatically downloaded from W3C and cached locally. The cache expires after 7 days to avoid hammering W3C servers with repeated downloads.

Recent Improvements (2025)

Validation Engine Enhancements
  • SimpleContent Validation: Full validation of text content in elements with simpleContent
  • List/Union Attribute Validation: Proper validation of attributes with list or union types
  • Type-Aware ID/IDREF Detection: Schema-based ID/IDREF validation instead of name-based heuristics
  • Substitution Group Type Checking: Verifies type compatibility for substitution group members
  • Wildcard Namespace Constraints: Proper error reporting for namespace constraint violations
Performance & Reliability
  • Cycle Detection: Added infinite recursion protection for circular type definitions
  • Memory Optimization: Reduced allocations in hot paths (ID/IDREF collection)
  • GC Efficiency: Pre-allocated maps and reusable singleton objects

See fixes.plan.md for detailed tracking of improvements and remaining enhancements.

Requirements

License

Copyright © 2025 AgentFlare AI

Contributing

This is a private repository. For questions or issues, please contact the maintainers.

  • go-xmldom - XML DOM and XPath library for Go
  • go-scxml - State Chart XML (SCXML) implementation

References

Documentation

Overview

union_list_types.go - Implementation of XSD union and list simple types validation

This file provides validation support for: - Union types: values that can be valid against any one of multiple member types - List types: space-separated lists of values of a specific item type - Proper namespace resolution for type references (fixed parseQName in schema.go) - Integration with the overall XSD validation framework

Index

Constants

View Source
const XSDNamespace = "http://www.w3.org/2001/XMLSchema"

XSDNamespace is the XML Schema namespace

Variables

View Source
var GlobalCache = NewSchemaCache("")

GlobalCache is the singleton schema cache

Functions

func AnalyzeTestFailures

func AnalyzeTestFailures(results []W3CTestResult) map[string]*FailureCategory

AnalyzeTestFailures categorizes test failures by XSD feature

func ApplyDefaultValue

func ApplyDefaultValue(elem xmldom.Element, defaultValue string) string

ApplyDefaultValue applies a default value to an element or attribute if it's empty

func CombineEnumerations

func CombineEnumerations(facets []FacetValidator) []string

CombineEnumerations combines multiple enumeration facets

func CountWildcardMatches

func CountWildcardMatches(elements []xmldom.Element, wildcard *AnyElement, targetNamespace string) int

CountWildcardMatches counts how many elements match a wildcard

func ExtractNamespaces

func ExtractNamespaces(doc xmldom.Document) map[string]NamespaceAttr

ExtractNamespaces extracts all xmlns namespace declarations from an XML document

func GenerateFailureReport

func GenerateFailureReport(categories map[string]*FailureCategory) string

GenerateFailureReport creates a detailed failure analysis report

func GetBuiltinTypeValidator

func GetBuiltinTypeValidator(typeName string) func(string) error

GetBuiltinTypeValidator returns a validator function for a built-in XSD type

func HasDefaultValue

func HasDefaultValue(decl interface{}) (string, bool)

HasDefaultValue checks if an element or attribute declaration has a default value

func HasFixedValue

func HasFixedValue(decl interface{}) (string, bool)

HasFixedValue checks if an element or attribute declaration has a fixed value

func IsBuiltinType

func IsBuiltinType(name string) bool

IsBuiltinType checks if a type is a built-in XSD type

func MatchesWildcard

func MatchesWildcard(elem xmldom.Element, namespace string, targetNamespace string) bool

MatchesWildcard checks if an element matches a wildcard's namespace constraint

func NormalizeWhiteSpace

func NormalizeWhiteSpace(value string, whiteSpace string) string

NormalizeWhiteSpace normalizes whitespace according to the facet value

func ValidateFacets

func ValidateFacets(value string, facets []FacetValidator, baseType Type) error

ValidateFacets validates a value against a list of facets

func ValidateListType

func ValidateListType(value string, list *List, schema *Schema) error

ValidateListType validates a value against a list type A list type represents a space-separated list of values of the item type

func ValidateSchemaFile

func ValidateSchemaFile(filename string) []error

ValidateSchemaFile validates an XSD schema file and returns any errors

func ValidateUnionType

func ValidateUnionType(value string, union *Union, schema *Schema) error

ValidateUnionType validates a value against a union type A union type allows a value to be valid against any one of its member types

Types

type AllowAnyContent

type AllowAnyContent struct{}

AllowAnyContent is a content model that allows any child elements

func (*AllowAnyContent) Validate

func (a *AllowAnyContent) Validate(element xmldom.Element, schema *Schema) []Violation

AllowAnyContent implementation

type AnyAttribute

type AnyAttribute struct {
	Namespace       string
	ProcessContents string
}

AnyAttribute represents xs:anyAttribute

type AnyElement

type AnyElement struct {
	Namespace       string
	ProcessContents string
	MinOcc          int
	MaxOcc          int
}

AnyElement represents xs:any wildcard

func (*AnyElement) MaxOccurs

func (ae *AnyElement) MaxOccurs() int

func (*AnyElement) MinOccurs

func (ae *AnyElement) MinOccurs() int

func (*AnyElement) Validate

func (ae *AnyElement) Validate(element xmldom.Element, schema *Schema) []Violation

type AttributeDecl

type AttributeDecl struct {
	Name    QName
	Type    Type
	Use     AttributeUse
	Default string
	Fixed   string
}

AttributeDecl represents an attribute declaration

type AttributeGroup

type AttributeGroup struct {
	Name       QName
	Attributes []*AttributeDecl
}

AttributeGroup represents a group of attributes

type AttributeUse

type AttributeUse string

AttributeUse represents attribute use

const (
	OptionalUse   AttributeUse = "optional"
	RequiredUse   AttributeUse = "required"
	ProhibitedUse AttributeUse = "prohibited"
)

type BuiltinType

type BuiltinType struct {
	Name      string
	Validator func(value string) error
}

BuiltinType represents a built-in XSD type

func GetBuiltinType

func GetBuiltinType(name string) *BuiltinType

GetBuiltinType returns a built-in type validator

type ComplexContent

type ComplexContent struct {
	Mixed       bool
	Base        QName
	Extension   *Extension
	Restriction *Restriction
}

ComplexContent represents complex content

func (*ComplexContent) MaxOccurs

func (cc *ComplexContent) MaxOccurs() int

func (*ComplexContent) MinOccurs

func (cc *ComplexContent) MinOccurs() int

func (*ComplexContent) Validate

func (cc *ComplexContent) Validate(element xmldom.Element, schema *Schema) []Violation

ComplexContent Validate implementation

type ComplexType

type ComplexType struct {
	QName              QName
	Content            Content
	Attributes         []*AttributeDecl
	AttributeGroup     []QName
	AnyAttribute       *AnyAttribute
	Mixed              bool
	Abstract           bool
	Final              map[string]bool // final constraints: extension, restriction
	DerivedByExtension bool            // set true if this type (or its base chain) includes an extension
}

ComplexType represents an XSD complex type

func (*ComplexType) Name

func (ct *ComplexType) Name() QName

func (*ComplexType) Validate

func (ct *ComplexType) Validate(element xmldom.Element, schema *Schema) []Violation

type Content

type Content interface {
	Validate(element xmldom.Element, schema *Schema) []Violation
}

Content represents element content model

type Diagnostic

type Diagnostic struct {
	Severity  Severity  `json:"severity"`
	Code      string    `json:"code"`
	Message   string    `json:"message"`
	Position  Position  `json:"position"`
	Tag       string    `json:"tag"`
	Attribute string    `json:"attribute,omitempty"`
	SpecRef   string    `json:"spec_ref,omitempty"`
	Hints     []string  `json:"hints,omitempty"`
	Related   []Related `json:"related,omitempty"`
}

Diagnostic represents a rustc-style validation diagnostic

type DiagnosticConverter

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

DiagnosticConverter converts XSD violations to rustc-style diagnostics

func NewDiagnosticConverter

func NewDiagnosticConverter(fileName, source string) *DiagnosticConverter

NewDiagnosticConverter creates a new converter

func (*DiagnosticConverter) Convert

func (dc *DiagnosticConverter) Convert(violations []Violation) []Diagnostic

Convert converts XSD violations to rustc-style diagnostics

type ElementDecl

type ElementDecl struct {
	Name              QName
	Type              Type
	MinOcc            int // Renamed to avoid conflict with Particle interface method
	MaxOcc            int // -1 for unbounded, renamed to avoid conflict
	Nillable          bool
	Abstract          bool
	SubstitutionGroup QName           // Head element this element can substitute for
	Block             map[string]bool // Disallowed substitutions from @block
	Default           string
	Fixed             string
	Constraints       []*IdentityConstraint // Identity constraints (key, keyref, unique)
}

ElementDecl represents an element declaration

func (*ElementDecl) MaxOccurs

func (ed *ElementDecl) MaxOccurs() int

func (*ElementDecl) MinOccurs

func (ed *ElementDecl) MinOccurs() int

Particle interface implementation for inline ElementDecl

func (*ElementDecl) Validate

func (ed *ElementDecl) Validate(element xmldom.Element, schema *Schema) []Violation

type ElementRef

type ElementRef struct {
	Ref    QName
	MinOcc int // Renamed to avoid conflict with method
	MaxOcc int // Renamed to avoid conflict with method
}

ElementRef represents a reference to an element

func (*ElementRef) MaxOccurs

func (er *ElementRef) MaxOccurs() int

func (*ElementRef) MinOccurs

func (er *ElementRef) MinOccurs() int

func (*ElementRef) Validate

func (er *ElementRef) Validate(element xmldom.Element, schema *Schema) []Violation

type EnumerationFacet

type EnumerationFacet struct {
	Values []string
}

EnumerationFacet validates against a set of allowed values

func (*EnumerationFacet) Name

func (f *EnumerationFacet) Name() string

func (*EnumerationFacet) Validate

func (f *EnumerationFacet) Validate(value string, baseType Type) error

type ErrorFormatter

type ErrorFormatter struct {
	Color           bool
	ShowFullElement bool
	ContextLines    int
}

ErrorFormatter provides rustc-style error formatting

func (*ErrorFormatter) Format

func (ef *ErrorFormatter) Format(diag Diagnostic, source string) string

Format formats a diagnostic in rustc style

type Extension

type Extension struct {
	Base         QName
	Attributes   []*AttributeDecl
	Content      Content
	AnyAttribute *AnyAttribute
}

Extension represents type extension

type Facet

type Facet interface {
	Validate(value string) error
}

Facet represents a constraining facet (deprecated - use FacetValidator from facets.go)

type FacetValidator

type FacetValidator interface {
	Validate(value string, baseType Type) error
	Name() string
}

FacetValidator validates a value against a facet constraint

func ParseFacet

func ParseFacet(name string, value string) FacetValidator

ParseFacet parses a facet element and returns the appropriate FacetValidator

type FailureCategory

type FailureCategory struct {
	Name        string
	Description string
	Count       int
	Examples    []W3CTestResult
}

FailureCategory represents a category of test failures

type Field

type Field struct {
	XPath string // XPath expression to select field value
}

Field represents the xs:field element

type FractionDigitsFacet

type FractionDigitsFacet struct {
	Value int
}

FractionDigitsFacet validates number of fraction digits

func (*FractionDigitsFacet) Name

func (f *FractionDigitsFacet) Name() string

func (*FractionDigitsFacet) Validate

func (f *FractionDigitsFacet) Validate(value string, baseType Type) error

type GroupRef

type GroupRef struct {
	Ref    QName
	MinOcc int
	MaxOcc int
}

GroupRef represents a reference to a model group

func (*GroupRef) MaxOccurs

func (gr *GroupRef) MaxOccurs() int

func (*GroupRef) MinOccurs

func (gr *GroupRef) MinOccurs() int

func (*GroupRef) Validate

func (gr *GroupRef) Validate(element xmldom.Element, schema *Schema) []Violation

type IdentityConstraint

type IdentityConstraint struct {
	Name     string
	Kind     IdentityConstraintKind
	Selector *Selector
	Fields   []*Field
	Refer    QName // For keyref, refers to a key or unique constraint
}

IdentityConstraint represents an identity constraint (key, keyref, or unique)

type IdentityConstraintKind

type IdentityConstraintKind string

IdentityConstraintKind represents the type of identity constraint

const (
	KeyConstraint    IdentityConstraintKind = "key"
	KeyRefConstraint IdentityConstraintKind = "keyref"
	UniqueConstraint IdentityConstraintKind = "unique"
)

type IdentityConstraintValidator

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

IdentityConstraintValidator validates identity constraints in XML documents

func NewIdentityConstraintValidator

func NewIdentityConstraintValidator() *IdentityConstraintValidator

NewIdentityConstraintValidator creates a new identity constraint validator

func (*IdentityConstraintValidator) AddConstraint

func (v *IdentityConstraintValidator) AddConstraint(constraint *IdentityConstraint)

AddConstraint adds an identity constraint to the validator

func (*IdentityConstraintValidator) Validate

Validate validates all identity constraints in the document

type Import

type Import struct {
	Namespace      string
	SchemaLocation string
}

Import represents an xs:import

type LengthFacet

type LengthFacet struct {
	Value int
}

LengthFacet validates exact length

func (*LengthFacet) Name

func (f *LengthFacet) Name() string

func (*LengthFacet) Validate

func (f *LengthFacet) Validate(value string, baseType Type) error

type List

type List struct {
	ItemType QName
}

List represents a list type

type MaxExclusiveFacet

type MaxExclusiveFacet struct {
	Value string
}

MaxExclusiveFacet validates maximum value (exclusive)

func (*MaxExclusiveFacet) Name

func (f *MaxExclusiveFacet) Name() string

func (*MaxExclusiveFacet) Validate

func (f *MaxExclusiveFacet) Validate(value string, baseType Type) error

type MaxInclusiveFacet

type MaxInclusiveFacet struct {
	Value string
}

MaxInclusiveFacet validates maximum value (inclusive)

func (*MaxInclusiveFacet) Name

func (f *MaxInclusiveFacet) Name() string

func (*MaxInclusiveFacet) Validate

func (f *MaxInclusiveFacet) Validate(value string, baseType Type) error

type MaxLengthFacet

type MaxLengthFacet struct {
	Value int
}

MaxLengthFacet validates maximum length

func (*MaxLengthFacet) Name

func (f *MaxLengthFacet) Name() string

func (*MaxLengthFacet) Validate

func (f *MaxLengthFacet) Validate(value string, baseType Type) error

type MinExclusiveFacet

type MinExclusiveFacet struct {
	Value string
}

MinExclusiveFacet validates minimum value (exclusive)

func (*MinExclusiveFacet) Name

func (f *MinExclusiveFacet) Name() string

func (*MinExclusiveFacet) Validate

func (f *MinExclusiveFacet) Validate(value string, baseType Type) error

type MinInclusiveFacet

type MinInclusiveFacet struct {
	Value string
}

MinInclusiveFacet validates minimum value (inclusive)

func (*MinInclusiveFacet) Name

func (f *MinInclusiveFacet) Name() string

func (*MinInclusiveFacet) Validate

func (f *MinInclusiveFacet) Validate(value string, baseType Type) error

type MinLengthFacet

type MinLengthFacet struct {
	Value int
}

MinLengthFacet validates minimum length

func (*MinLengthFacet) Name

func (f *MinLengthFacet) Name() string

func (*MinLengthFacet) Validate

func (f *MinLengthFacet) Validate(value string, baseType Type) error

type ModelGroup

type ModelGroup struct {
	Kind      ModelGroupKind // sequence, choice, all
	Particles []Particle
	MinOcc    int // Renamed to avoid conflict with method
	MaxOcc    int // Renamed to avoid conflict with method
}

ModelGroup represents a group of elements

func (*ModelGroup) MaxOccurs

func (mg *ModelGroup) MaxOccurs() int

func (*ModelGroup) MinOccurs

func (mg *ModelGroup) MinOccurs() int

func (*ModelGroup) Validate

func (mg *ModelGroup) Validate(element xmldom.Element, schema *Schema) []Violation

type ModelGroupKind

type ModelGroupKind string

ModelGroupKind represents the kind of model group

const (
	SequenceGroup ModelGroupKind = "sequence"
	ChoiceGroup   ModelGroupKind = "choice"
	AllGroup      ModelGroupKind = "all"
)

type NamespaceAttr

type NamespaceAttr struct {
	Prefix string      // Namespace prefix (empty for default namespace)
	URI    string      // Namespace URI
	Attr   xmldom.Attr // The xmlns attribute node
}

NamespaceAttr holds a namespace URI and its attribute node

type Particle

type Particle interface {
	MinOccurs() int
	MaxOccurs() int
	Validate(element xmldom.Element, schema *Schema) []Violation
}

Particle represents a particle in a content model

type PatternFacet

type PatternFacet struct {
	Pattern string
	// contains filtered or unexported fields
}

PatternFacet validates against a regular expression pattern

func (*PatternFacet) Name

func (f *PatternFacet) Name() string

func (*PatternFacet) Validate

func (f *PatternFacet) Validate(value string, baseType Type) error

type PatternLoader

type PatternLoader struct {
	Pattern string           // Regex pattern to match against namespace
	Loader  SchemaLoaderFunc // Function to load the schema
	// contains filtered or unexported fields
}

PatternLoader associates a pattern with a loader function

type Position

type Position struct {
	File   string `json:"file"`
	Line   int    `json:"line"`
	Column int    `json:"column"`
	Offset int64  `json:"offset"`
}

Position contains source position information for a node

type ProcessContentsMode

type ProcessContentsMode string

ProcessContentsMode defines how wildcard content should be processed

const (
	// StrictProcess requires the element/attribute to be validated against its declaration
	StrictProcess ProcessContentsMode = "strict"
	// LaxProcess validates if a declaration is found, otherwise allows it
	LaxProcess ProcessContentsMode = "lax"
	// SkipProcess allows the element/attribute without validation
	SkipProcess ProcessContentsMode = "skip"
)

type QName

type QName struct {
	Namespace string
	Local     string
}

func (QName) String

func (q QName) String() string

String returns the string representation of a QName

type Related struct {
	Label    string   `json:"label"`
	Position Position `json:"position"`
}

Related points to a related location in the source

type Restriction

type Restriction struct {
	Base   QName
	Facets []FacetValidator
	// For complexContent restrictions
	Content      Content
	Attributes   []*AttributeDecl
	AnyAttribute *AnyAttribute
}

Restriction represents a restriction on a type

type Schema

type Schema struct {
	TargetNamespace      string
	ElementDecls         map[QName]*ElementDecl
	TypeDefs             map[QName]Type
	AttributeGroups      map[QName]*AttributeGroup
	Groups               map[QName]*ModelGroup
	Imports              []*Import
	ImportedSchemas      map[string]*Schema // Map of imported schemas by location
	SubstitutionGroups   map[QName][]QName  // Maps head element to list of substitutable elements
	BlockDefault         map[string]bool    // xs:schema@blockDefault tokens
	FinalDefault         map[string]bool    // xs:schema@finalDefault tokens
	ElementFormDefault   string             // "qualified" or "unqualified" (default)
	AttributeFormDefault string             // "qualified" or "unqualified" (default)

	// Options
	StrictContentModel bool // If true, use strict content-model validation
	// contains filtered or unexported fields
}

Schema represents a compiled XSD schema

func LoadSchema

func LoadSchema(filename string) (*Schema, error)

LoadSchema loads and parses an XSD schema from a file

func LoadSchemaFromString

func LoadSchemaFromString(content string, baseDir string) (*Schema, error)

LoadSchemaFromString loads a schema from a string with import/include support

func LoadSchemaWithImports

func LoadSchemaWithImports(location string) (*Schema, error)

LoadSchemaWithImports is a convenience function

func Parse

func Parse(doc xmldom.Document) (*Schema, error)

Parse parses an XSD schema from an XML document

func (*Schema) ResolveAttributeGroups

func (s *Schema) ResolveAttributeGroups(ct *ComplexType) []*AttributeDecl

ResolveAttributeGroups resolves all attribute group references for a complex type

func (*Schema) ValidateContentModels added in v0.1.4

func (s *Schema) ValidateContentModels() error

ValidateContentModels performs determinism (UPA) checks on compiled content models

type SchemaCache

type SchemaCache struct {
	BasePath string // Base path for resolving relative schema locations
	// contains filtered or unexported fields
}

SchemaCache manages cached XSD schemas using sync.OnceValue per project rules

func NewSchemaCache

func NewSchemaCache(basePath string) *SchemaCache

NewSchemaCache creates a new schema cache

func (*SchemaCache) Clear

func (sc *SchemaCache) Clear()

Clear removes all cached schemas

func (*SchemaCache) Get

func (sc *SchemaCache) Get(location string) (*Schema, error)

Get retrieves a schema from cache or loads it if not present

func (*SchemaCache) GetOrLoad

func (sc *SchemaCache) GetOrLoad(location string, doc xmldom.Document) (*Schema, error)

GetOrLoad gets a schema from cache or loads from provided document

func (*SchemaCache) PreloadCommonTypes

func (sc *SchemaCache) PreloadCommonTypes()

PreloadCommonTypes preloads commonly used XSD types for performance

func (*SchemaCache) Remove

func (sc *SchemaCache) Remove(location string)

Remove removes a specific schema from cache

func (*SchemaCache) SetBasePath

func (sc *SchemaCache) SetBasePath(path string)

SetBasePath sets the base path for resolving relative schema locations

type SchemaLoader

type SchemaLoader struct {
	// Base directory for resolving relative paths
	BaseDir string
	// contains filtered or unexported fields
}

SchemaLoader handles loading schemas with import/include support

func NewSchemaLoader

func NewSchemaLoader(config SchemaLoaderConfig) (*SchemaLoader, error)

NewSchemaLoader creates a new schema loader with the given configuration

func NewSchemaLoaderSimple

func NewSchemaLoaderSimple(baseDir string) *SchemaLoader

NewSchemaLoaderSimple creates a simple schema loader with just a base directory This is a convenience function for when you don't need custom loaders

func (*SchemaLoader) LoadSchemaForNamespace

func (sl *SchemaLoader) LoadSchemaForNamespace(namespace string) (*Schema, error)

LoadSchemaForNamespace is deprecated - use LoadSchemasFromNamespaces instead This method cannot provide the xmlns attribute node that loaders need

func (*SchemaLoader) LoadSchemaWithImports

func (sl *SchemaLoader) LoadSchemaWithImports(location string) (*Schema, error)

LoadSchemaWithImports loads a schema and all its imports/includes

func (*SchemaLoader) LoadSchemasFromNamespaces

func (sl *SchemaLoader) LoadSchemasFromNamespaces(namespaces map[string]NamespaceAttr) (*Schema, error)

LoadSchemasFromNamespaces loads schemas for the given namespaces using configured loaders Returns a combined schema with all loaded schemas merged

type SchemaLoaderConfig

type SchemaLoaderConfig struct {
	// Base directory for resolving relative paths
	BaseDir string

	// HTTP client for remote loading (optional, defaults to http.DefaultClient)
	HTTPClient *http.Client

	// Pattern-based loaders for namespace resolution
	Loaders []PatternLoader
}

SchemaLoaderConfig configures a SchemaLoader with dependency injection

type SchemaLoaderFunc

type SchemaLoaderFunc func(attr xmldom.Attr) (*Schema, error)

SchemaLoaderFunc is a function that loads a schema for a given namespace attribute node The attr parameter is the xmlns attribute node from which the namespace URI can be extracted

type SchemaRegistry

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

SchemaRegistry manages multiple schemas for different namespaces

func NewSchemaRegistry

func NewSchemaRegistry() *SchemaRegistry

NewSchemaRegistry creates a new schema registry

func (*SchemaRegistry) GetForNamespace

func (sr *SchemaRegistry) GetForNamespace(namespace string) (*Schema, bool)

GetForNamespace retrieves the schema for a namespace

func (*SchemaRegistry) Register

func (sr *SchemaRegistry) Register(namespace string, schema *Schema)

Register registers a schema for a namespace

func (*SchemaRegistry) RegisterFile

func (sr *SchemaRegistry) RegisterFile(namespace, location string) error

RegisterFile registers a schema from a file

func (*SchemaRegistry) SetDefault

func (sr *SchemaRegistry) SetDefault(schema *Schema)

SetDefault sets the default schema for elements without namespaces

func (*SchemaRegistry) Validate

func (sr *SchemaRegistry) Validate(doc xmldom.Document) []Violation

ValidateWithRegistry validates a document using multiple namespace schemas

type SchemaValidator

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

SchemaValidator validates that an XSD schema document conforms to XSD rules

func NewSchemaValidator

func NewSchemaValidator() *SchemaValidator

NewSchemaValidator creates a new schema validator

func (*SchemaValidator) ValidateSchema

func (sv *SchemaValidator) ValidateSchema(doc xmldom.Document) []error

ValidateSchema validates that a schema document conforms to XSD rules

type Selector

type Selector struct {
	XPath string // XPath expression to select nodes
}

Selector represents the xs:selector element

type Severity

type Severity string

Severity represents the severity level of a diagnostic

const (
	SeverityError   Severity = "error"
	SeverityWarning Severity = "warning"
	SeverityInfo    Severity = "info"
)

type SimpleContent

type SimpleContent struct {
	Base        QName
	Extension   *Extension
	Restriction *Restriction
}

SimpleContent represents simple content in a complex type

func (*SimpleContent) MaxOccurs

func (sc *SimpleContent) MaxOccurs() int

func (*SimpleContent) MinOccurs

func (sc *SimpleContent) MinOccurs() int

func (*SimpleContent) Validate

func (sc *SimpleContent) Validate(element xmldom.Element, schema *Schema) []Violation

type SimpleType

type SimpleType struct {
	QName       QName
	Base        QName
	Restriction *Restriction
	List        *List
	Union       *Union
}

SimpleType represents an XSD simple type

func (*SimpleType) Name

func (st *SimpleType) Name() QName

func (*SimpleType) Validate

func (st *SimpleType) Validate(element xmldom.Element, schema *Schema) []Violation

type TotalDigitsFacet

type TotalDigitsFacet struct {
	Value int
}

TotalDigitsFacet validates total number of digits

func (*TotalDigitsFacet) Name

func (f *TotalDigitsFacet) Name() string

func (*TotalDigitsFacet) Validate

func (f *TotalDigitsFacet) Validate(value string, baseType Type) error

type Type

type Type interface {
	Name() QName
	Validate(element xmldom.Element, schema *Schema) []Violation
}

Type is the interface for all XSD types

type Union

type Union struct {
	MemberTypes []QName
}

Union represents a union type

type Validator

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

Validator validates XML documents against XSD schemas

func NewValidator

func NewValidator(schema *Schema) *Validator

NewValidator creates a new validator for a schema

func (*Validator) Validate

func (v *Validator) Validate(doc xmldom.Document) []Violation

Validate validates an XML document against the schema

type Violation

type Violation struct {
	Element   xmldom.Element
	Attribute string
	Code      string
	Message   string
	Expected  []string
	Actual    string
}

Violation represents a validation error

func ValidateAnyAttribute

func ValidateAnyAttribute(attr xmldom.Node, wildcard *AnyAttribute, schema *Schema) []Violation

ValidateAnyAttribute validates attributes against xs:anyAttribute wildcard constraints

func ValidateAnyElement

func ValidateAnyElement(elem xmldom.Element, wildcard *AnyElement, schema *Schema) []Violation

ValidateAnyElement validates an element against xs:any wildcard constraints

func ValidateAttributeFixedDefault

func ValidateAttributeFixedDefault(attr xmldom.Node, decl *AttributeDecl, elem xmldom.Element) []Violation

ValidateAttributeFixedDefault validates fixed and default values for an attribute

func ValidateChildSequence

func ValidateChildSequence(elem xmldom.Element, expected []string) []Violation

ValidateChildSequence validates a sequence of child elements

func ValidateElementFixedDefault

func ValidateElementFixedDefault(elem xmldom.Element, decl *ElementDecl) []Violation

ValidateElementFixedDefault validates fixed and default values for an element

func ValidateFixedValue

func ValidateFixedValue(value, fixed string, isElement bool, name string) *Violation

ValidateFixedValue validates that an element or attribute has the required fixed value

func ValidateWildcardOccurrences

func ValidateWildcardOccurrences(matchCount int, wildcard *AnyElement) []Violation

ValidateWildcardOccurrences validates that wildcard occurrences are within bounds

type W3CAnnotation

type W3CAnnotation struct {
	Documentation string `xml:"documentation"`
}

W3CAnnotation contains test documentation

type W3CCurrentStatus

type W3CCurrentStatus struct {
	Status string `xml:"status,attr"` // "accepted", "disputed", etc.
	Date   string `xml:"date,attr"`
}

W3CCurrentStatus tracks test acceptance status

type W3CDocReference

type W3CDocReference struct {
	Href string `xml:"href,attr"`
}

W3CDocReference links to specification documentation

type W3CExpected

type W3CExpected struct {
	Validity string `xml:"validity,attr"` // "valid", "invalid", or "notKnown"
}

W3CExpected indicates expected validity

type W3CInstanceDoc

type W3CInstanceDoc struct {
	Href string `xml:"href,attr"`
}

W3CInstanceDoc references an instance document

type W3CInstanceTest

type W3CInstanceTest struct {
	Name             string           `xml:"name,attr"`
	InstanceDocument W3CInstanceDoc   `xml:"instanceDocument"`
	Expected         W3CExpected      `xml:"expected"`
	Current          W3CCurrentStatus `xml:"current"`
}

W3CInstanceTest tests whether an instance validates against a schema

type W3CSchemaDoc

type W3CSchemaDoc struct {
	Href string `xml:"href,attr"`
}

W3CSchemaDoc references a schema document

type W3CSchemaTest

type W3CSchemaTest struct {
	Name           string           `xml:"name,attr"`
	SchemaDocument W3CSchemaDoc     `xml:"schemaDocument"`
	Expected       W3CExpected      `xml:"expected"`
	Current        W3CCurrentStatus `xml:"current"`
}

W3CSchemaTest tests whether a schema is valid or invalid

type W3CTestGroup

type W3CTestGroup struct {
	Name          string            `xml:"name,attr"`
	Annotation    *W3CAnnotation    `xml:"annotation"`
	DocReference  *W3CDocReference  `xml:"documentationReference"`
	SchemaTests   []W3CSchemaTest   `xml:"schemaTest"`
	InstanceTests []W3CInstanceTest `xml:"instanceTest"`
}

W3CTestGroup represents a test group containing related tests

type W3CTestResult

type W3CTestResult struct {
	TestSet      string
	TestGroup    string
	TestName     string
	TestType     string // "schema" or "instance"
	Expected     string // "valid", "invalid", "notKnown"
	Actual       string // "valid", "invalid", "error"
	Passed       bool
	Error        error
	SchemaPath   string
	InstancePath string
}

W3CTestResult captures the result of running a test

type W3CTestRunner

type W3CTestRunner struct {
	TestSuiteDir       string
	Results            []W3CTestResult
	Verbose            bool
	StrictContentModel bool
	Grep               string // optional substring filter on set/group/test names
}

W3CTestRunner runs W3C XSD conformance tests

func NewW3CTestRunner

func NewW3CTestRunner(testSuiteDir string) *W3CTestRunner

NewW3CTestRunner creates a test runner for the W3C test suite

func (*W3CTestRunner) GenerateReport

func (r *W3CTestRunner) GenerateReport() string

GenerateReport generates a summary report of test results

func (*W3CTestRunner) LoadTestSet

func (r *W3CTestRunner) LoadTestSet(metadataPath string) (*W3CTestSet, error)

LoadTestSet loads a W3C test set from an XML file

func (*W3CTestRunner) RunAllTests

func (r *W3CTestRunner) RunAllTests(pattern string) error

RunAllTests discovers and runs all test metadata files

func (*W3CTestRunner) RunMetadataFile

func (r *W3CTestRunner) RunMetadataFile(metadataPath string) error

RunMetadataFile runs all tests from a single metadata file

func (*W3CTestRunner) RunTestSet

func (r *W3CTestRunner) RunTestSet(testSet *W3CTestSet, metadataDir string)

RunTestSet runs all tests in a test set

type W3CTestSet

type W3CTestSet struct {
	XMLName     xml.Name       `xml:"testSet"`
	Contributor string         `xml:"contributor,attr"`
	Name        string         `xml:"name,attr"`
	TestGroups  []W3CTestGroup `xml:"testGroup"`
}

W3CTestSet represents a test set from the W3C XSD test suite

type WhiteSpaceFacet

type WhiteSpaceFacet struct {
	Value string // "preserve", "replace", or "collapse"
}

WhiteSpaceFacet handles whitespace normalization

func (*WhiteSpaceFacet) Name

func (f *WhiteSpaceFacet) Name() string

func (*WhiteSpaceFacet) Validate

func (f *WhiteSpaceFacet) Validate(value string, baseType Type) error

type WildcardNamespaceConstraint

type WildcardNamespaceConstraint struct {
	Mode       string   // "##any", "##other", "##targetNamespace", "##local", or space-separated list
	Namespaces []string // Explicit list of allowed namespaces (when not using ##modes)
}

WildcardNamespaceConstraint represents namespace constraints for wildcards

func ParseNamespaceConstraint

func ParseNamespaceConstraint(value string) *WildcardNamespaceConstraint

ParseNamespaceConstraint parses a namespace attribute value into a constraint

func (*WildcardNamespaceConstraint) Matches

func (c *WildcardNamespaceConstraint) Matches(namespace, targetNamespace string) bool

Matches checks if a namespace matches this constraint

Directories

Path Synopsis
cmd
test_schema command
validate command
w3c_test command

Jump to

Keyboard shortcuts

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