xsd

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 12 Imported by: 0

README

xsd

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

xsd is a secure XML Schema 1.0 parser, compiler, validator, serializer, and builder for Go. It is intended to provide the schema layer for wsdl and SOAP tooling without performing implicit file or network access.

[!WARNING] The module follows stable v1 compatibility. The XML Schema 1.0 support matrix is complete and the pinned XSTS gate passes; XML Schema 1.1 is intentionally outside the stable scope.

compiler, err := compile.New(compile.Options{Resolver: resolver})
if err != nil {
	return err
}
set, err := compiler.Compile(ctx, compile.Source{
	URI:     "https://example.test/order.xsd",
	Content: schema,
})
if err != nil {
	return err
}
validator, err := validate.New(set, validate.Options{})
if err != nil {
	return err
}
result, err := validator.Validate(ctx, instance)

Parsing and validation reject DTDs. Compilation uses a deny-by-default resolver and bounded schema graphs. See the documentation index, the live support matrix, and specification provenance. Observable ambiguities and package policy are recorded in the specification decision register.

Run make check for formatting, static analysis, tests, the race detector, and provenance checks.

Ecosystem

Use the Golib documentation portal to choose companion packages, supported stacks, recipes, and operations guidance.

Documentation

Overview

Package xsd parses XML Schema documents into a specification-oriented model.

Parsing never performs file or network I/O. Resource resolution is an explicit compilation concern handled by the resolve and compile packages.

Index

Constants

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

Variables

View Source
var (
	// ErrDTDForbidden reports a DTD or other XML directive. XSD documents do
	// not need DTD processing and directives are rejected before compilation.
	ErrDTDForbidden = errors.New("xsd: DTD and XML directives are forbidden")
	// ErrNotSchema reports that the document element is not xs:schema.
	ErrNotSchema = errors.New("xsd: root element is not an XML Schema schema")
	// ErrLimitExceeded reports that an explicit parser, serializer, or compiler
	// bound was exceeded.
	ErrLimitExceeded = errors.New("xsd: resource limit exceeded")
)

Functions

func Marshal

func Marshal(document *Document) ([]byte, error)

Marshal serializes a schema document deterministically as UTF-8 XML using conservative resource limits.

func MarshalWithOptions

func MarshalWithOptions(document *Document, options MarshalOptions) ([]byte, error)

MarshalWithOptions serializes a schema document deterministically as UTF-8 XML while enforcing explicit output, nesting, and component-work limits.

func NormalizeIdentityXPath

func NormalizeIdentityXPath(expression string) string

NormalizeIdentityXPath removes XML whitespace permitted around tokens in the XML Schema 1.0 identity-constraint XPath subset. Whitespace that would separate two name tokens is retained so a later grammar check rejects it.

Types

type Annotation

type Annotation struct {
	ID             string
	Documentation  []Documentation
	AppInformation []AppInfo
}

Annotation represents xs:annotation content retained by the parser.

type AppInfo

type AppInfo struct {
	ID      string
	Source  string
	Content string
}

AppInfo preserves machine-readable xs:appinfo content.

type Attribute

type Attribute struct {
	ID               string
	Name             string
	Type             QName
	Default          string
	Fixed            string
	DefaultSet       bool
	FixedSet         bool
	ValueNamespaces  map[string]string
	InlineSimpleType *SimpleType
	Annotation       *Annotation
}

Attribute is a global attribute declaration.

type AttributeGroup

type AttributeGroup struct {
	ID                       string
	Name                     string
	Attributes               []AttributeUse
	References               []QName
	Wildcard                 *Wildcard
	Annotation               *Annotation
	AttributeGroupReferences []AttributeGroupReference
}

AttributeGroup is a named global collection of attribute uses.

type AttributeGroupReference

type AttributeGroupReference struct {
	ID         string
	Ref        QName
	Annotation *Annotation
}

AttributeGroupReference preserves an attribute-group reference annotation.

type AttributeUse

type AttributeUse struct {
	ID               string
	Name             string
	Namespace        string
	Ref              QName
	Type             QName
	Form             Form
	Use              AttributeUseKind
	Default          string
	Fixed            string
	DefaultSet       bool
	FixedSet         bool
	ValueNamespaces  map[string]string
	InlineSimpleType *SimpleType
	Annotation       *Annotation
}

AttributeUse is an attribute use within a complex type.

type AttributeUseKind

type AttributeUseKind string

AttributeUseKind controls whether an attribute use is optional, required, or prohibited.

const (
	AttributeOptional   AttributeUseKind = "optional"
	AttributeRequired   AttributeUseKind = "required"
	AttributeProhibited AttributeUseKind = "prohibited"
)

type ComplexType

type ComplexType struct {
	ID                       string
	Name                     string
	Base                     QName
	SimpleBase               QName
	InlineSimpleType         *SimpleType
	SimpleFacets             []Facet
	Derivation               Derivation
	SimpleContent            bool
	Abstract                 bool
	Mixed                    bool
	MixedSet                 bool
	Block                    DerivationSet
	Final                    DerivationSet
	Content                  *ModelGroup
	Attributes               []AttributeUse
	AttributeGroupRefs       []QName
	AttributeGroupReferences []AttributeGroupReference
	AttributeWildcard        *Wildcard
	Annotation               *Annotation
	ContentAnnotation        *Annotation
	DerivationAnnotation     *Annotation
	ContentID                string
	DerivationID             string
}

ComplexType is a global complex type definition.

type Compositor

type Compositor string

Compositor identifies an XML Schema model group compositor.

const (
	Sequence Compositor = "sequence"
	Choice   Compositor = "choice"
	All      Compositor = "all"
)

type Derivation

type Derivation string

Derivation is an XML Schema derivation or substitution control token.

const (
	DerivationExtension    Derivation = "extension"
	DerivationRestriction  Derivation = "restriction"
	DerivationSubstitution Derivation = "substitution"
	DerivationList         Derivation = "list"
	DerivationUnion        Derivation = "union"
)

type DerivationSet

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

DerivationSet represents blockDefault and finalDefault values. The zero value is an empty set.

func (DerivationSet) All

func (s DerivationSet) All() bool

All reports whether the lexical value was #all.

func (DerivationSet) Contains

func (s DerivationSet) Contains(value Derivation) bool

Contains reports whether a derivation is in the set. #all contains every derivation.

func (DerivationSet) String

func (s DerivationSet) String() string

String returns the deterministic XML Schema lexical representation.

type Diagnostic

type Diagnostic struct {
	Severity Severity
	Code     string
	Message  string
	Path     string
	Location Location
}

Diagnostic is a stable machine-readable schema or instance finding.

type Document

type Document struct {
	ID                   string
	SystemID             string
	BaseURI              string
	TargetNamespace      string
	Namespaces           map[string]string
	ElementFormDefault   Form
	AttributeFormDefault Form
	BlockDefault         DerivationSet
	FinalDefault         DerivationSet
	Version              string
	Language             string
	Annotations          []Annotation
	References           []SchemaReference
	Redefinitions        []Redefinition
	Elements             []Element
	Attributes           []Attribute
	SimpleTypes          []SimpleType
	ComplexTypes         []ComplexType
	ModelGroups          []ModelGroupDefinition
	AttributeGroups      []AttributeGroup
	Notations            []Notation
}

Document is an XML Schema schema document. Component declarations are populated in source order so deterministic serialization is possible.

func Parse

func Parse(ctx context.Context, source []byte, options ParseOptions) (*Document, error)

Parse decodes one XML Schema document without resolving external resources.

type Documentation

type Documentation struct {
	ID       string
	Source   string
	Language string
	Content  string
	Markup   string
}

Documentation represents human-readable xs:documentation content.

type Element

type Element struct {
	ID                  string
	Name                string
	Namespace           string
	Type                QName
	Ref                 QName
	Form                Form
	Abstract            bool
	Nillable            bool
	Default             string
	Fixed               string
	DefaultSet          bool
	FixedSet            bool
	ValueNamespaces     map[string]string
	Block               DerivationSet
	Final               DerivationSet
	IdentityConstraints []IdentityConstraint
	InlineSimpleType    *SimpleType
	InlineComplexType   *ComplexType
	TargetNamespace     string
	SubstitutionGroup   QName
	Annotation          *Annotation
}

Element is a global element declaration.

type Facet

type Facet struct {
	ID         string
	Kind       FacetKind
	Value      string
	Fixed      bool
	Namespaces map[string]string
	Annotation *Annotation
}

Facet preserves one restriction facet in source order.

type FacetKind

type FacetKind string

FacetKind identifies an XML Schema constraining facet.

const (
	FacetLength         FacetKind = "length"
	FacetMinLength      FacetKind = "minLength"
	FacetMaxLength      FacetKind = "maxLength"
	FacetPattern        FacetKind = "pattern"
	FacetEnumeration    FacetKind = "enumeration"
	FacetWhiteSpace     FacetKind = "whiteSpace"
	FacetMaxInclusive   FacetKind = "maxInclusive"
	FacetMaxExclusive   FacetKind = "maxExclusive"
	FacetMinInclusive   FacetKind = "minInclusive"
	FacetMinExclusive   FacetKind = "minExclusive"
	FacetTotalDigits    FacetKind = "totalDigits"
	FacetFractionDigits FacetKind = "fractionDigits"
)

type Form

type Form string

Form controls whether locally declared element or attribute names are namespace-qualified in instance documents.

const (
	FormUnqualified Form = "unqualified"
	FormQualified   Form = "qualified"
)

type IdentityConstraint

type IdentityConstraint struct {
	ID                 string
	TargetNamespace    string
	Name               string
	Kind               IdentityKind
	Refer              QName
	Selector           string
	SelectorID         string
	Fields             []string
	FieldIDs           []string
	Namespaces         map[string]string
	Annotation         *Annotation
	SelectorAnnotation *Annotation
	FieldAnnotations   []*Annotation
}

IdentityConstraint preserves the XML Schema identity XPath subset.

type IdentityKind

type IdentityKind string

IdentityKind identifies an xs:unique, xs:key, or xs:keyref constraint.

const (
	IdentityUnique IdentityKind = "unique"
	IdentityKey    IdentityKind = "key"
	IdentityKeyRef IdentityKind = "keyref"
)

type Location

type Location struct {
	SystemID string
	Line     int
	Column   int
	Offset   int64
}

Location identifies an offset in an input resource. Line and Column are one-based when known; Offset is a zero-based byte offset.

type MarshalOptions

type MarshalOptions struct {
	MaxOutputBytes int64
	MaxDepth       int
	MaxComponents  int
}

MarshalOptions bounds deterministic schema serialization. Zero values use conservative defaults; negative values are invalid.

type ModelGroup

type ModelGroup struct {
	ID         string
	Compositor Compositor
	Particles  []Particle
	MinOccurs  uint64
	MaxOccurs  uint64
	Unbounded  bool
	OccursSet  bool
	Annotation *Annotation
}

ModelGroup is a sequence, choice, or all group.

type ModelGroupDefinition

type ModelGroupDefinition struct {
	ID         string
	Name       string
	Content    *ModelGroup
	Annotation *Annotation
}

ModelGroupDefinition is a named global model group.

type Notation

type Notation struct {
	ID         string
	Name       string
	Public     string
	System     string
	Annotation *Annotation
}

Notation is a global xs:notation declaration.

type ParseError

type ParseError struct {
	Location Location
	Err      error
}

ParseError adds stable resource location information to a parsing failure.

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

Unwrap supports errors.Is and errors.As.

type ParseOptions

type ParseOptions struct {
	SystemID         string
	MaxDocumentBytes int64
	MaxDepth         int
	MaxElements      int
}

ParseOptions configures a single document parse. A zero byte limit uses a conservative default; a negative value is invalid.

type Particle

type Particle struct {
	ID         string
	MinOccurs  uint64
	MaxOccurs  uint64
	Unbounded  bool
	Element    *Element
	Group      *ModelGroup
	GroupRef   QName
	Wildcard   *Wildcard
	Annotation *Annotation
}

Particle applies occurrence constraints to an element or nested group.

type ProcessContents

type ProcessContents string

ProcessContents controls validation for declarations matched by a wildcard.

const (
	ProcessStrict ProcessContents = "strict"
	ProcessLax    ProcessContents = "lax"
	ProcessSkip   ProcessContents = "skip"
)

type QName

type QName struct {
	Namespace string
	Local     string
}

QName is an expanded XML qualified name.

type Redefinition

type Redefinition struct {
	Reference       SchemaReference
	SimpleTypes     []SimpleType
	ComplexTypes    []ComplexType
	ModelGroups     []ModelGroupDefinition
	AttributeGroups []AttributeGroup
}

Redefinition contains the declarations nested in xs:redefine.

type ReferenceKind

type ReferenceKind string

ReferenceKind identifies a schema composition directive.

const (
	ReferenceInclude  ReferenceKind = "include"
	ReferenceImport   ReferenceKind = "import"
	ReferenceRedefine ReferenceKind = "redefine"
)

type SchemaReference

type SchemaReference struct {
	ID         string
	Kind       ReferenceKind
	Namespace  string
	Location   string
	URI        string
	Annotation *Annotation
}

SchemaReference preserves an include, import, or redefine in source order. Location is the lexical schemaLocation; URI is resolved against xml:base and the document SystemID without loading it.

type Severity

type Severity string

Severity is the stable importance of a validation diagnostic.

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

type SimpleType

type SimpleType struct {
	ID                string
	Name              string
	Variety           SimpleVariety
	Final             DerivationSet
	Base              QName
	InlineBase        *SimpleType
	Facets            []Facet
	ItemType          QName
	InlineItem        *SimpleType
	MemberTypes       []QName
	InlineMembers     []SimpleType
	Annotation        *Annotation
	VarietyAnnotation *Annotation
	VarietyID         string
}

SimpleType is a global simple type definition.

type SimpleVariety

type SimpleVariety string

SimpleVariety identifies restriction, list, or union construction.

const (
	SimpleRestriction SimpleVariety = "restriction"
	SimpleList        SimpleVariety = "list"
	SimpleUnion       SimpleVariety = "union"
)

type Wildcard

type Wildcard struct {
	ID              string
	Namespaces      []string
	ProcessContents ProcessContents
	Annotation      *Annotation
}

Wildcard constrains namespaces and validation for xs:any or xs:anyAttribute.

Directories

Path Synopsis
Package builder provides checked helpers for constructing schema documents.
Package builder provides checked helpers for constructing schema documents.
Package compile resolves XML Schema document graphs into immutable sets.
Package compile resolves XML Schema document graphs into immutable sets.
Package datatype implements XML Schema datatype lexical and value spaces.
Package datatype implements XML Schema datatype lexical and value spaces.
Package resolve defines explicit XML Schema resource resolution boundaries.
Package resolve defines explicit XML Schema resource resolution boundaries.
Package validate checks XML instances against immutable compiled schema sets.
Package validate checks XML instances against immutable compiled schema sets.
Package xsdtest runs XML Schema test-set metadata against xsd.
Package xsdtest runs XML Schema test-set metadata against xsd.

Jump to

Keyboard shortcuts

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