go-xml
XML Schema 1.0/1.1 validation, XPath 2.0/3.0/3.1, XQuery 3.1 and XSLT 2.0/3.0 in pure Go. No cgo,
no JVM, no libxml2 — one go get, and it cross-compiles like any Go package.
go get github.com/knroy/go-xml/v2
This is v2. v2 changes the exported API (node fields become methods,
a smaller node layout, a split evaluation context); see the v2.0.0 section
of CHANGELOG.md and Migrating to v2,
which has before/after code for each change and a tool that rewrites most of
it. v1 stays at github.com/knroy/go-xml and still receives fixes on the
v1 branch.
Validate a document against a schema:
schema, err := xsd.LoadFile("schemas/invoice.xsd", xsd.Options{})
tree, err := xdm.ParseString(src, xdm.ParseOptions{})
err = schema.Validate(tree.Root, xsd.ValidateOptions{})
Every error carries the spec’s code and a path — cvc-datatype-valid.1 at
/invoice/total — not just “invalid”.
For a document you did not write, use schema.ValidateContext(ctx, ...): it is
the same call with a deadline, and identity-constraint checking is where an
untrusted document can make validation expensive. See
docs/security.md. Validate only checks and never writes
to the tree; to get a typed tree, use schema.ValidateCopy, which annotates a
copy (options).
The packages
|
|
xdm |
the parser and the XDM tree everything else reads |
xsd |
XML Schema 1.0 and 1.1: assembly, validation, PSVI annotation |
xpath |
XPath 2.0, 3.0 and 3.1: lexer, parser, evaluator, fn: library |
xquery |
XQuery 3.1: constructors, FLWOR, the prolog |
xslt |
XSLT 2.0 and 3.0: templates, modes, keys, grouping, serialisation |
c14n |
Canonical XML 1.0 and 1.1, Exclusive C14N: the octets XML signatures digest |
Safe by default
Aimed at input arriving over the wire, so the defaults are the settings you
would choose for untrusted documents. Options{} is already hardened:
- DOCTYPE is refused, which closes XXE and entity expansion at the door
- No network access — a
schemaLocation cannot make this process fetch
xsi:schemaLocation is ignored, so a document cannot pick its own schema
- Size, node-count and depth limits are on, sized for a general service
See docs/security.md for the threat model and
docs/server.md for a validating HTTP endpoint measured
against XXE, billion-laughs and resource exhaustion.
Building and checking
go build ./...
go test -race ./...
tests/check.sh runs everything that has to pass before a change is done —
build, vet, unit tests, race, every W3C suite and the production corpora.
docs/testing.md covers the layers, the environment
variables, the ratchet, and how to read a result:
tests/check.sh fast # no external suites
GOXSLT_UBL=<dir> GOXSLT_CII=<dir> tests/check.sh # everything
A change that must not move observable behaviour is also checked output for
output: tests/record.sh <dir> records what every suite case and corpus
document produces, and go run ./tests/recdiff compare -allow tests/recdiff/allow.txt <a> <b> lists each case that differs between two
recordings (docs/testing.md).
The real-world stylesheet corpora are found under testdata/ by default, or
pointed at a checkout of your own:
git clone --depth 1 https://github.com/docbook/xslt3ng testdata/xsltng
git clone --depth 1 https://github.com/xspec/xspec testdata/xspec
DocBook needs its localisation files generated first — the build compiles them
from src/main/locale/, and this engine can do it:
for f in testdata/xsltng/src/main/locale/*.xml; do
go run ./cmd/go-xml -xsl testdata/xsltng/src/main/xslt/modules/xform-locale.xsl \
-allow-dir testdata/xsltng -o testdata/xsltng/src/main/xslt/locale/"$(basename "$f")" "$f"
done
A missing suite is reported as skipped; a suite that is present but produces no
result is a failure. A check that did not run must not look like one that
succeeded.
One dependency: golang.org/x/text, for Unicode normalisation and
language-sensitive collation. Nothing else is outside the standard library.
Requires Go 1.25 or later. The floor is measured, not nominal: regexp
learned the Unicode category Cn in 1.25, and building on 1.24 costs four
conformance cases; golang.org/x/text v0.35 and later require 1.25 as well.
See docs/testing.md.
Build with a supported, patched Go (1.26.9 or 1.27.2 and later at the time of
v2.0.1). Several fixes go-xml relies on ship only in Go releases: os.Root,
which confines every file go-xml reads or writes, and net/http and
crypto/tls, which the opt-in xsd/xsdnet resolver uses. Go 1.25 no longer
receives them. See docs/security.md.
Live test
go-xml fiddle
runs a stylesheet against a document in the browser and shows you the result.
No Go toolchain, no checkout — paste the XSLT or XQuery you already have and
see what this engine makes of it.
It is the work of Martin Honnen, who built
and maintains it as a project of his own.
Status
|
|
| XPath 2.0 |
100.00% of the W3C QT3 suite (15,217 of 15,217 in scope) |
| XPath 3.0 |
100.00% of the W3C QT3 suite (19,362 of 19,362 in scope) |
| XPath 3.1 |
100.00% of the W3C QT3 suite (22,054 of 22,054 in scope); maps, arrays, the lookup operator, the JSON family, and fn:transform, measured since it became callable from XPath |
| XQuery 3.1 |
100.00% of the W3C QT3 suite (30,529 of 30,530 in scope); constructors, FLWOR, the prolog, try/catch, switch, typeswitch, windows, and both halves of import — module and schema. Schema import brought 416 cases into scope and 318 more passes; the 1 remaining failure, contextDecl-052, is a W3C fixture defect catalogued in conformance-gaps.md |
| XSLT 2.0 |
99.87% of the W3C XSLT suite filtered to 2.0 (6,194 of 6,202 in scope); verified against Saxon-HE 12.4 on two production corpora |
| XSLT 3.0 |
99.85% of the W3C XSLT suite filtered to 3.0 (11,505 of 11,522 in scope). Streaming is now measured rather than excluded, which is why the denominator grew by 2,862 cases; every one of the 151 cases that wants the XTSE3430 refusal gets it — see Where it fails. Also measured against DocBook xslTNG and XSpec — see Real-world stylesheets |
| XSD 1.0 |
99.90% of the W3C xsdtests instance tests (24,974 of 25,000); 99.98% of its schema-validity tests (14,385 of 14,388) |
| XSD 1.1 |
99.90% instance (26,218 of 26,244); 99.97% schema-validity (15,350 of 15,354); opt-in via Version11 |
| RELAX NG |
100.00% of James Clark’s spectest (965 of 965 assertions); XML and compact syntax, from Go and from go-xml validate -rng |
| DTD |
content models, attribute defaults, enumerations, ID/IDREF; external subset, parameter entities across both subsets, conditional sections — via dtd.Load with a caller-supplied resolver, nothing fetched by default |
| Tests |
3,690 func Test declarations, clean under -race (a few subtests skip without the corpora below) |
| Production schemas |
UBL 2.1, UN/CEFACT CII, Factur-X/ZUGFeRD, Peppol BIS 3.0 — 88 schemas load, instances validate clean |
| API |
1.2; the exported surface is stable and additive over 1.1, and a breaking change means 2.0 with a new module path |
Read this before adopting it. Three things are commonly assumed and are not
true here:
-
Both halves of the XSD numbers carry a residue of disagreements — 29 on
1.0 and 30 on 1.1 — and where they are schema-validity failures, a schema
invalid in one of those ways is accepted rather than reported. They are
listed in Where it fails, along with what the suite skips and why; most
of them — 54 of 59 — are cases the W3C itself has queried or filed a bug
against, including every one of the 44 MS-Regex disagreements, which
are a single open bug. A further 16 cases on 1.0 and 14 on 1.1 are excluded
from both sides of the ratio because the suite marks them
indeterminate — the working group left the area underspecified, so no
result is prescribed and none is scored.
-
A backreference to a variable-width group is refused, by design. RE2
has no backreferences, which is also why no pattern can hang this engine.
Where the group has a fixed width the backreference is resolved exactly,
in linear time — that covers (a)\1, ([md])[aeiou]\1 and the like. Where
it can vary, (a*)\1, there is more than one way to split the match and RE2
reports only one, so the answer is FORX0002 rather than a guess. The XML
Schema pattern facet has no backreference at all and rejects them outright,
which is conformant: Appendix F’s grammar has no form for one.
-
XSLT 3.0 is the youngest of the measured numbers, at 99.84%, and still
the one to check against your own stylesheets first. It has no
concentration left: none of the 19 failures wants the XTSE3430 refusal
(the §19.8 analysis raises it for all 151 W3C cases that want it), and the
19 are fixture defects, deliberate divergences or implementation-defined, each
recorded with its verdict. No single feature is systematically weak. The
corpus differential against Saxon remains stronger evidence for real
stylesheets than the percentage.
Neither XSLT number is directly comparable to the XPath and XSD ones. There
is no maintained XSLT 2.0 suite, so both are the XSLT 3.0 suite filtered by
each test’s declared version dependency — a different kind of measurement
from running a suite written for the version under test.
Streamed execution covers xsl:source-document streamable="yes" and a
principal input read through Stylesheet.TransformReader:
one xsl:for-each or xsl:iterate over a record path such as //rec or
doc/rec, or one xsl:value-of/xsl:copy-of/xsl:sequence over one
record path such as sum(doc/rec/@v), read one record at a time; and,
through the streamed core, sequence constructors of literal result
elements, xsl:element, xsl:copy, xsl:choose, loops, split selects,
xsl:apply-templates into streamable modes, xsl:for-each-group
(adjacent, starting-with, ending-with), xsl:try, streamable attribute
sets, calls on stylesheet functions whose body is one xsl:sequence
(recursive ones too, over values or a match’s grounded copy), bodies with
instructions planned in the caller’s plan, call frames for recursion, and
a used package’s functions,
accumulators, xsl:fork and xsl:map, xsl:merge over streamable
sources, set operators, climbing paths, kept text nodes, xsl:message,
xsl:comment, xsl:processing-instruction and xsl:result-document, and
validated inputs; TransformOptions.Output and
SecondaryOutput write the results as they are made. Of the 2,930 W3C
cases that touch streaming, 2,661 stream; 262 are refused as the spec
requires or ask for no streamed input, and the 7 left are proved not
streamable (a cycle, an invalid URI, an input that is already a tree, a
mode the spec does not guarantee); a few that stream hold a copy of the
whole document and save no memory (see known gaps).
Otherwise the streaming cases are in
scope and counted: the stylesheet-level half of streaming, the §19.8
streamability analysis that refuses a construct with XTSE3430, is
implemented and measured. A construct the streamed core does not take
still executes, by building the tree instead: correct results, in memory
proportional to the document. system-property('xsl:supports-streaming')
reports yes; streaming-fallback is not claimed. What a streamable stylesheet computes is
another question — the spec requires it to be the same as a non-streaming
evaluation, so the si-* sets, which assert results rather than memory
behaviour, are in scope and nearly all pass. Where it fails sets out the
rest.
Every remote-reference mechanism — DOCTYPE, fn:doc, file reads — is off
unless enabled; see Security defaults.
What this is
Eight packages, each usable on its own:
| Package |
What it holds |
xdm |
The XQuery/XPath data model: typed atomic values, the node tree, an XML parser |
xpath |
XPath 2.0, 3.0 and 3.1: lexer, parser, evaluator, and the fn:, map:, array: and math: function libraries |
xquery |
XQuery 3.1: constructors, FLWOR, the prolog, and the XQuery-only expression forms |
xslt |
XSLT 2.0 and 3.0: pattern matching, the stylesheet compiler, the transform runtime, serialisation |
xsd |
XML Schema 1.0 and 1.1: the component model, schema assembly, content models, facets, identity constraints |
dtd |
DTD validation: content models, attribute defaults, ID/IDREF, external subsets |
relaxng |
RELAX NG: the derivative algorithm, the section 7 restrictions, the XSD datatype library, the compact syntax |
c14n |
Canonical XML 1.0, Exclusive Canonical XML 1.0 and Canonical XML 1.1, over any node set, streamed |
cmd/go-xml |
A command-line transformer, validator and XQuery runner |
Documentation
- docs/xquery.md — XQuery 3.1: entry points, output,
external variables, options
- docs/validation.md — XSD, DTD and RELAX NG
validation, Schematron, and which kind of “valid” you actually need. Start
here if you came to check a document against a schema.
- docs/xsd.md — the schema validator in detail: 1.0 versus
1.1, resolvers and what they will fetch, the PSVI, limits, concurrency, and
what the conformance figures cover.
- docs/server.md — compile once, transform or validate
per request: a complete XSLT service, a hardened XSD validation endpoint
(measured against XXE, billion-laughs and resource exhaustion), timeouts,
limits, hot-reloading rule sets.
- docs/recipes.md — batching, splitting, HTML
rendering, parameters, custom resolvers, standalone XPath, finding elements
without XPath.
- docs/c14n.md — Canonical XML for XML-DSig, SAML and
WS-Security: choosing an algorithm, node sets, the enveloped-signature
transform, and the verification still to do.
- docs/options.md — every option in
xdm, xpath,
xsd, xslt, xquery, dtd and c14n: what each field does, what the
zero value means, and the limits that bound a parse, a validation and a
transform.
- SECURITY.md — how to report a vulnerability, and what
counts as one.
- docs/security.md — threat model and the results of
three audits: XXE is closed, entity expansion is bounded per reference
rather than per entity, and the third audit’s findings are written up
including the one left open.
- CHANGELOG.md — what each release contains, and what the
1.0 stability promise does and does not cover.
- RELEASE.md — how a release is cut: the manual steps in the
order that matters, and what the tag-push workflow checks and refuses.
- docs/benchmark.md — go-xml against Saxon-HE,
BaseX, Jing, Xerces-J, libxml2 and
encoding/xml on DocBook, e-invoicing,
XMark, schema validation and parsing, cold and warm, with outputs checked
for agreement before anything is timed. The harness is
go-xml-bench. Streaming against
the tree is measured in-repo (go run ./tests/streambench): 15–20 MB of RSS
at any input size, against 1.6–2.4 GB for the tree at 564 MB.
- docs/profiling.md — where v2’s time and memory go
per workload, how to profile and A/B a change, and the ideas measured and
rejected.
- docs/known-gaps.md — every measured failure and why
it is still open, including the fix attempts that were reverted because they
cost more than they gained.
Architecture
The layering is strict and one-directional. Both host languages use XPath,
XPath uses XDM, and XDM knows nothing about any of them — which is what keeps
the data model honest when a host language needs something awkward.
XSLT and XQuery are siblings rather than layers: neither uses the other, and
both compile their expressions with xpath and build their result trees with
xdmbuild. That sharing is the reason XQuery arrived at 99% in one push
rather than being a second engine — the expression language and the ~437
functions were already there and already at 100%.
The one crossing is fn:load-xquery-module: xquery registers its loader
with xpath when imported, so a stylesheet gets the function whenever the
program links xquery, without xslt importing it.
cmd/go-xml command-line transformer
│
┌─────▼─────────────────────────┐ ┌──────────────────────────────┐
│ xslt stylesheet compiler │ │ xquery constructors · FLWOR │
│ patterns · templates │ │ the prolog │
│ instructions · output │ │ │
└─────┬─────────────────────────┘ └─────┬────────────────────────┘
│ │
│ ┌─────────────────────────┘
│ │ both build result trees with xdmbuild, and hand
│ │ every expression to xpath to compile and evaluate
┌─────▼────────▼─────────────────────────────────┐
│ xpath lexer → parser → optimiser → runtime │
│ functions · operators · type system │
└─────┬──────────────────────────────────────────┘
│ every value is an Item; every result a Sequence
┌─────▼──────────────────────────────────────────┐
│ xdm nodes · atomic values · sequences │
│ QNames · the XML parser │
└────────────────────────────────────────────────┘
XDM is the centre, not a wrapper over encoding/xml. Documents are read by
this library’s own tokeniser, internal/xmltok, which reports names exactly as
written: XSLT needs the prefix and the xmlns declarations, because namespace
nodes are addressable on the namespace axis and a literal result element must
serialise with the prefix its author wrote. The tree is built here, and no
library code imports encoding/xml.
Three types carry the model. Item is a closed interface over *Node,
*Atomic, and *Opaque (engine-internal state threaded through the same
interface). Sequence is a flat []Item — XDM has no nested sequences, and
every constructor maintains that. Atomic is a tagged union rather than
interface{}, because XPath’s type system is not Go’s: xs:decimal is a
big.Rat so 0.1 + 0.2 is exactly 0.3, and xs:dateTime is not time.Time
because XML Schema timezones are optional and “absent” is a distinct value
from +00:00.
Static and dynamic context are separate types. Namespace bindings, the
default element namespace, and the function library are resolved at parse
time through NamespaceResolver. The context item, position, size, variables,
clock, and timezone live on Context at evaluation time. Merging them is a
trap: XSLT compiles one pattern once and evaluates it against every node, so
anything static must not be re-resolved per node.
Compilation is separate from execution. Compile is the expensive step and
produces an immutable Stylesheet; Transform does not mutate it. That is what
makes one compiled rule set safe to share across goroutines, and it is tested
under -race with a shared source tree as well as a shared stylesheet.
Patterns are matched right to left. An XSLT match pattern looks like a
path but means “does this node match”, not “navigate from here”. Evaluating the
path and testing membership is quadratic; matching upward from the candidate is
O(depth), which is the difference between finishing on a large document and not.
Use
sheetTree, err := xdm.ParseString(stylesheetSource, xdm.ParseOptions{})
sheet, err := xslt.Compile(sheetTree.Root, xslt.CompileOptions{})
docTree, err := xdm.ParseString(documentSource, xdm.ParseOptions{})
result, err := sheet.Transform(ctx, docTree.Root, xslt.TransformOptions{})
fmt.Println(result.String()) // serialised per xsl:output (html defaults to HTML5)
result.Tree() // or keep navigating it
result.Messages // xsl:message output, collected not printed
result.Secondary // documents from xsl:result-document
Each SecondaryResult carries the Href the stylesheet asked for, its own
Nodes, and the OutputSettings that apply to it, and serialises itself:
for _, doc := range result.Secondary {
fmt.Println(doc.Href, doc.String())
}
Nothing is written to disk unless you write it — see Security defaults.
A large document can be streamed rather than built. TransformReader reads
it once, as the transform runs, when the stylesheet starts in a mode declared
streamable="yes" whose rules are guaranteed streamable; otherwise it is
exactly xdm.Parse then Transform, so the result, errors and limits are the
same either way. One difference from Transform of a parsed tree is the
spec’s: in a mode declared streamable the global context item is absent
(XSLT 3.0 §2.3.2), on both paths. A stylesheet compiled from its
xsl:stylesheet element streams as one compiled from its document node,
including an element inside a larger tree such as an XML-DSig ds:Transform:
f, err := os.Open("big.xml")
defer f.Close()
result, err := sheet.TransformReader(ctx, f, xslt.TransformOptions{
SourceParseOptions: xdm.ParseOptions{
BaseURI: "file:///data/big.xml", // fn:base-uri, relative fn:doc
DocumentURI: "file:///data/big.xml", // fn:document-uri
MaxBytes: -1, // the default refuses over 64 MB
MaxNodes: -1,
},
})
With Output set, the principal result is serialized there as it is built,
so memory holds only what is not yet written:
result, err := sheet.TransformReader(ctx, f, xslt.TransformOptions{
Output: os.Stdout,
})
Result.Tree() and Result.Nodes are then nil, and on an error the writer
may already hold part of the result. An xsl:try’s output is written
provisionally and taken back if the try catches an error.
With SecondaryOutput set, each xsl:result-document is written to the writer
the function returns for the result’s absolute URI, as it is produced, and
closed at its end, instead of being kept in Result.Secondary; a
file-splitting transform then holds neither its input nor its outputs:
result, err := sheet.TransformReader(ctx, f, xslt.TransformOptions{
Output: os.Stdout,
SecondaryOutput: func(uri string) (io.WriteCloser, error) {
// The URI is the stylesheet's choice: confine it (docs/security.md).
name := path.Base(uri)
if name == "." || name == "/" {
return nil, fmt.Errorf("unusable href %q", uri)
}
return os.Create(filepath.Join(outDir, name))
},
})
Inside an xsl:try, or a streamed xsl:source-document or xsl:merge (which a
failure may re-run on the tree), a result is written once it is final; an error
returned by the function or by Close is the transform’s.
SourceValidation validates the principal input against the stylesheet’s
schema (xsl:import-schema); TransformReader validates it as it reads it,
with the typed values and defaults of the tree’s typed copy and the same
error either way:
sheet, err := xslt.Compile(sheetTree.Root, xslt.CompileOptions{SchemaResolver: &xsd.FileResolver{}})
result, err := sheet.TransformReader(ctx, f, xslt.TransformOptions{
SourceValidation: xslt.SourceStrict, // XTTE1510 if the document is not valid
Output: os.Stdout,
})
Nothing outside the rules may read the document for it to stream: no typed
xsl:global-context-item, no applicable accumulator that is not streamable or
that the stream cannot compute. A global variable reading . does not read
the document: the global context item is absent for a streamed input, so it
raises XPDY0002, streamed or not. In a streamable
mode the identity template’s <xsl:apply-templates select="@*|node()"/> is
refused with XTSE3430 (§19.8.8.4 makes the union crawling); write it as
<xsl:apply-templates select="@*"/><xsl:apply-templates select="node()"/>,
which streams. See known gaps for the full conditions.
Compile is the expensive step and Transform does not mutate the compiled
stylesheet, so compile once and transform concurrently — the test suite
exercises that under -race.
XPath alone:
ctx := xpath.NewContext(docTree.Root, xpath.Builtins())
seq, err := xpath.Eval("sum(//invoice/@total)", ctx, nil)
XQuery, which compiles once and evaluates concurrently the same way a
stylesheet does. A query returns a sequence; serialising it is a separate step:
q, err := xquery.Compile(`
<totals>{
for $i in //invoice
group by $y := year-from-date(xs:date($i/@date))
order by $y
return <year n="{$y}">{ sum($i/@total) }</year>
}</totals>`, xquery.Options{})
seq, err := q.Eval(xpath.NewContext(docTree.Root, xpath.Builtins()))
err = xslt.Serialize(os.Stdout, seq, xslt.OutputSettings{OmitXMLDecl: true}, nil)
// <totals><year n="2023">7</year><year n="2024">15</year></totals>
The xs:date cast is not decoration: an attribute in an unvalidated document
is xs:untypedAtomic, and year-from-date refuses it with XPTY0004 rather
than guessing.
See docs/xquery.md for options, external variables and what
is not implemented.
Canonical XML, for a signature digest or a semantic comparison. There is no
default algorithm: the specification you are implementing names one.
sum, err := c14n.Digest(sha256.New(), elem, c14n.Options{
Algorithm: c14n.Exclusive10,
InclusiveNamespacePrefixes: c14n.ParsePrefixList("#default xsi"),
})
same, err := c14n.Equal(a.Root, b.Root, c14n.Options{Algorithm: c14n.Inclusive11})
See docs/c14n.md for node sets, the enveloped-signature
transform, and the xml:base and xml:id rules that separate 1.0 from 1.1.
CLI:
go-xml -xsl transform.xsl input.xml
go-xml -xsl rules.xsl -p year=2024 -allow-dir ./codelists invoice.xml
# Start at a named template. A stylesheet that generates its own content
# needs no source document, so none is given.
go-xml -xsl generate.xsl -initial-template main
# Validate a directory: report every failure rather than stopping at the first.
go-xml -xsl rules.xsl -keep-going invoices/*.xml
# Pin the clock and timezone so the run is reproducible.
go-xml -xsl report.xsl -now 2024-01-15T09:00:00Z -timezone 240 in.xml
# Report the source line each validation failure occurred on.
go-xml -xsl rules.xsl -track-positions invoice.xml
# Write the documents an xsl:result-document stylesheet produces.
go-xml -xsl split.xsl -result-dir ./out catalogue.xml
| Flag |
Effect |
-xsl |
the stylesheet to apply (required) |
-o |
write to a file instead of stdout |
-p name=value |
supply a top-level xsl:param; repeatable |
-allow-dir |
open xsl:include/xsl:import/xsl:import-schema/doc()/document() to further directories, each covering its subdirectories to any depth; the stylesheet’s own directory is always readable. Empty or whitespace segments are ignored, never read as the working directory. It says where, not what: raw text, external entities and XInclude each need their own flag as well |
-allow-doctype |
permit a DOCTYPE in the source |
-catalog DIR |
answer xsl:import-schema’s references to the W3C schemas (XMLSchema.xsd, xml.xsd) from local copies in DIR instead of leaving them unresolved; see validation.md |
-timeout |
bound the transform, and the -xinclude pass before it (default 60s) |
-max-items N |
items the transform may materialise (default 5,000,000; -1 removes the bound) |
-max-bytes N |
largest input document (default 64 MB; -1 removes the limit) |
-initial-template |
start at a named template instead of matching the root; no input document is then needed |
-mode |
initial mode for apply-templates |
-messages |
print xsl:message output to stderr |
-now |
pin fn:current-dateTime (RFC 3339) |
-timezone |
implicit timezone in minutes |
-track-positions |
record source line/column; see below |
-validate strict|lax |
validate each source against the schema the stylesheet imports with xsl:import-schema before the transform, so its nodes carry schema types and atomise to typed values; lax skips an undeclared document element |
-result-dir |
where xsl:result-document outputs with an href are written; one with no href goes to the principal output instead |
-keep-going |
continue a batch past a failure, still exiting non-zero |
The exit status is 0 only if every input transformed.
The CLI does not link net/http: HTTPResolver lives in its own package,
xsd/xsdnet, which the CLI does not import.
The CLI is built with profile-guided optimisation from the committed
cmd/go-xml/default.pgo (regenerate it with tests/pgo.sh), which go build
and go install use automatically: on v2, 1–6% less CPU in a warm loop and
1–2% per cold run. A program embedding the library gains only from a profile
of its own in its main package.
The CLI runs with Go’s allocation sampling off (runtime.MemProfileRate 0).
It does not link runtime/pprof, so the Go linker turns the sampling off; a
build that links it (a -cpuprofile flag, net/http/pprof) would pay up to
10% more CPU on the DocBook stylesheets, whose deep recursion makes sampling
expensive.
go-xml xquery runs an XQuery main module. The optional input document is
the context item; the result is serialized with the query’s own
declare option output:* parameters.
go-xml xquery -q report.xq -p year=2024 -o out.xml invoice.xml
go-xml xquery -q generate.xq -now 2024-01-15T09:00:00Z
It takes -o, -p (an external variable, as xs:string), -allow-dir,
-allow-doctype, -allow-external-entities, -allow-unparsed-text,
-catalog, -max-items, -max-bytes, -timeout, -now and -validate, with the transform’s meanings and defaults: import module ... at, import schema ... at, doc() and unparsed-text() read only
the query’s own directory and the -allow-dir roots. -validate strict|lax
validates the input document against the schema the query imports before the
query runs. A query can type nodes itself with validate { }, but a query
that declares a typed context item (declare context item as document-node(schema-element(...))) is checked before its body runs, so only
-validate can satisfy it from the command line.
Design notes
Compilation has an optimisation stage. Compile folds closed
sub-expressions to literals before evaluation, so (1 + 2) * 3 costs one
literal load per node rather than three operations — 13.77 ns for a whole
arithmetic expression. Two conditions guard every rewrite: the expression must
be closed (no variable, context item, or context-dependent function), and the
rewrite must preserve errors as well as values. 1 idiv 0 is deliberately not
folded, because refusing a stylesheet at compile time for an error in a branch
that is never taken would be wrong.
Foldable functions are an allowlist rather than a denylist. A user-defined
function is never folded even if it happens to be pure, because the library it
resolves through is supplied by the caller.
Errors carry their specification code as a field. A message is prose that
may be reworded; a code is what a caller branches on and what a conformance
suite compares. xdm.ErrorCode(err) returns it, unwrapping as it goes, and
falls back to recognising the code where an error still carries it as a message
prefix. The rendered text is unchanged, so nothing reading error strings had to
move.
This is not cosmetic: making codes inspectable let the QT3 harness stop
accepting any error where a specific one was expected, which immediately found
961 wrong codes that the loose check had been hiding.
Aggregates over a range are arithmetic, not iteration. An integer range is
fully determined by its bounds, so nothing has to be built to answer a question
about it:
|
|
count(lo to hi) |
hi - lo + 1 |
sum(lo to hi) |
n(first + last) / 2 |
min / max |
the bounds themselves |
avg |
the midpoint |
sum(1 to 10000000) returns 50000005000000 in 6 MB rather than materialising
ten million values at 1.9 GB. The series is summed in big.Int, because
n(first+last) overflows int64 well before the bounds do —
sum(1 to 5000000000000) is about 1.25 × 10²⁵ and this engine returns it
exactly, where Saxon refuses the range outright (its sequences are capped at
int32).
The general form of the idea is a lazy sequence type carrying its own
cardinality — don’t ask a sequence to enumerate itself if the operation can be
answered from its structure. That would mean making xdm.Sequence an
interface rather than a slice, which every operation across three packages
indexes and ranges over directly. The narrower version gets the same result for
the cases that arise, because lo to hi is the only XPath 2.0 construct that
can name a sequence too large to hold: a path expression is bounded by the
document, a literal sequence by the length of the stylesheet.
The recognition is deliberately narrow — only a bare to directly under the
aggregate. A predicate, a for, or a comma sequence changes which items
survive, so those evaluate normally and meet the item budget instead:
sum((1 to 10)[. mod 2 = 0]) is 30, not 55. That narrowness is what lets the
budget stay strict, and it is what the tests check hardest.
Sequences and types, not node-sets and strings. XPath 1.0 had four types
and coerced freely between them. 2.0 replaces that with sequences of typed
items and explicit promotion rules, and most of the difficulty of the language
is there rather than in the syntax. xs:decimal is a big.Rat, so 0.1 + 0.2
is exactly 0.3; xs:integer div xs:integer yields a decimal; the four
numeric types promote along integer → decimal → float → double before any
comparison. Implementing this with float64 throughout would pass a
surprising number of tests and then quietly misreport a monetary total.
Dates are not time.Time. XML Schema dates carry an optional timezone,
where “absent” is a distinct value from +00:00; they exceed the year range of
int64 nanoseconds; and their seconds have arbitrary fractional precision. The
xdm.DateTime type models all three, because a validator that treats an
unzoned date as UTC gets comparisons wrong at the day boundary.
Patterns are matched right to left. An XSLT match pattern looks like a
path expression but means “does this node match”, not “navigate from here”. The
obvious implementation — evaluate the path, test membership — is quadratic.
Matching from the candidate node upward makes it O(depth), which is the
difference between a transform that finishes on a large document and one that
does not.
Templates are pre-sorted. Selection scans the template list and stops at
the first match, because the list is ordered by (import precedence, priority,
declaration order) at compile time. Default priorities follow the spec’s
values, since getting them wrong silently selects the wrong rule — a much
harder failure to debug than a crash.
The parser separates namespace nodes from attributes. internal/xmltok
hands xdm each name with its prefix and every xmlns declaration as an
attribute; xdm resolves prefixes itself and turns the declarations into
namespace nodes, which XSLT addresses on the namespace axis and serialises
with the prefix the author wrote. encoding/xml would discard both, and its
name tables are XML 1.0 First Edition, which is why the library owns its
tokeniser.
Instructions write to a builder, not to a string. A sequence constructor
produces a stream of nodes and atomic values: xsl:element opens a node that
later instructions add children to, an attribute added after children is an
error, and a variable with content becomes a navigable temporary tree.
Returning strings from each instruction would make all of that impossible.
That one decision is why xsl:result-document needed no architectural change:
every instruction already took a builder as a parameter, so a secondary
document is just a second builder rather than a rewrite of the output path.
Unset must not look like a real answer. Source positions are stored on the
node as the byte offset plus one, so the zero value reads as “unknown”.
Nodes are built with plain struct literals in two dozen places across the
transform layer; had the raw offset been stored, every constructed node would
have claimed to start at line 1, and a construction site added later would
have inherited the bug invisibly. The same reasoning runs through the API:
gx:line-number() returns the empty sequence rather than 0, because a report
naming line 0 for every failure is worse than one naming none.
Concurrency and memory
A compiled Stylesheet is immutable and safe to share: compile once, transform
from many goroutines. The tests exercise that under -race rather than
asserting it — including a shared parsed source tree, which is the stronger
claim, since it means evaluation never writes back into the document.
That last claim was false until an audit found the counter-example, and it is
worth recording how it hid. xsl:sequence handed source nodes straight to the
output builder, which called AppendChild on them — and AppendChild rewrote
the node’s parent and tree pointers, while Finalize renumbered its document
order. So reading from the document mutated it. (In v2 nothing can relink a
node: a tree is built top-down, and a node becomes content as a copy.) The visible symptom was not a
race at all:
<xsl:variable name="v"><xsl:sequence select="/r/b"/></xsl:variable>
Against <r><a/><b/><c/></r>, a later string-join(/r/*/name(), ',') returned
a,c,b. The variable is never used; evaluating it was enough to reorder the
input. xsl:copy-of was correct all along because it deep-copies. The guard now
lives in appendNode rather than at the two call sites, so a node that already
belongs to a tree is copied whatever reaches it.
The concurrency tests had covered key indexes, xsl:message and the regex cache
— everything that looked like shared state — and missed this because it did not
look like state at all.
A loaded xsd.Schema is the same kind of value: immutable once assembled, safe
to validate from many goroutines. Its one piece of lazily-built state, the
content-model cache, is a sync.Map for that reason. The tests exercise the
claim under -race rather than asserting it — validating cold schemas from
sixteen goroutines released together, so the cache is written under contention
rather than read from a warm one, and validating documents that carry the same
xs:ID values concurrently, since identity and ID/IDREF tables are the state
most likely to have been hung off the schema by mistake. Loading is covered
too, including a schema that declares over the built-in XML-namespace
attributes while others load beside it.
Per-transform state lives on a runtime struct that is copied on every focus
change. Anything that must survive those copies — xsl:message output,
xsl:result-document results — is held through a pointer, and there are tests
that fail if a transform ever sees another’s.
The one piece of process-wide mutable state is the compiled-regex cache, and
it was an unbounded leak. The original reasoning was that patterns come
from stylesheets and so form a fixed set; that is wrong, because
matches($s, $node/@pattern) compiles a pattern taken from document data. A
long-running validator retained one compiled regexp per distinct pattern it had
ever seen — 17.6 MB after 20,000 patterns, still climbing. It is now bounded at
1024 entries and clears wholesale when full, which measures at 0.6 MB for the
same load and stays flat at five times it. Each entry is also weighed by the
bytes its compiled program retains, and the cache clears when the total would
pass 32 MiB, so a large pattern is compiled once and cached rather than
recompiled on every call; only an entry over about 4 MB is not kept.
Clearing rather than evicting one entry at a time is deliberate: a true LRU
needs a lock on every read, which costs more than it saves when the working
set is the handful of patterns a stylesheet actually contains. Correctness does
not depend on a hit — every entry is reproducible from its key — and
TestRegexCacheStaysCorrectWhenCleared pins that.
The backtracking engine’s single-character-atom cache had the same defect and
now has the same bound. It is reached only when SetBacktrackingRegex(true) is
set — off by default, and set only by cmd/go-xml’s -backtracking-regex flag —
so it was an opt-in availability issue rather than a default-configuration one.
TestCharAtomCacheIsBounded counts the entries rather
than the heap, because one atom is small enough that the map size is the only
exact signal.
FileResolver’s document cache exists because fn:doc is defined to return
the same node for the same URI within one execution, so doc('x') is doc('x')
requires it. It is mutex-guarded, and now capped at 256 documents and 32 MB of source. It had been
unbounded on the reasoning that the directories the caller opened with
-allow-dir bound it in practice — true for the size of the set, but the
process holds every document it has ever parsed for its whole lifetime, and a
stylesheet chooses which ones to fetch. Reaching the cap costs one reparse.
Results never pin their source. xsl:copy-of deep-copies, so holding a
Result from a 20,000-element document costs a few hundred KB rather than the
document.
Optimisation
Compilation has an optimisation stage between the parser and the runtime.
Everything it does is measured below; nothing is included because it seemed
likely to help.
Constant folding. A closed sub-expression is evaluated once at compile time
and replaced with a literal, so (1 + 2) * 3 - 4 idiv 2 costs one literal load
per node instead of five operations — 13.8 ns for the whole expression.
Two conditions guard every rewrite:
- The expression must be closed: no variable, no context item, no function
that reads the dynamic context.
1 + 2 folds; position() + 1 does not.
- The rewrite must preserve errors as well as values.
1 idiv 0 is
deliberately not folded — refusing a stylesheet at compile time for an error
in a branch that is never taken would be wrong.
Folding is bounded per compilation: every fold in one compile shares a
4,096-item budget and CompileOptions.Context, and a fold that would exceed
either is simply not done, so it runs at evaluation time instead.
Foldable functions are an allowlist, not a denylist. A user-defined function is
never folded even if it happens to be pure, because the library it resolves
through is supplied by the caller.
Aggregates over a range are arithmetic. An integer range is determined by
its bounds, so nothing is built to answer a question about it: count is
hi - lo + 1, sum is the arithmetic series, min/max are the bounds.
sum(1 to 10000000) returns 50000005000000 in 6 MB rather than
materialising ten million values at 1.9 GB. The series is summed in
big.Int because n(first+last) overflows int64 long before the bounds do —
sum(1 to 5000000000000) is exact here, and Saxon refuses the range outright
(its sequences cap at int32).
The recognition is deliberately narrow: only a bare to directly under the
aggregate. A predicate, a for, or a comma sequence changes which items
survive, so those evaluate normally — sum((1 to 10)[. mod 2 = 0]) is 30, not
55.
Compiled regexes are cached, bounded. Schematron applies the same handful
of patterns to every node, and regexp.Compile dominates otherwise. The cache
was originally unbounded on the reasoning that patterns come from stylesheets —
which is wrong, because matches($s, $node/@pattern) compiles a pattern from
document data. That leaked 17.6 MB per 20,000 distinct patterns and never
shrank. It is now capped at 1024 entries and clears wholesale when full, which
measures 0.6 MB for the same load.
Templates are pre-sorted, not indexed. Selection scans the template list
and stops at the first match, because the list is ordered by (import
precedence, priority, declaration order) at compile time. A per-element-name
index would make dispatch cheaper in principle — but profiling a 67-template
renderer put findTemplateFrom nowhere near the top, so it is not implemented.
See Where it is slow below.
What was tried and reverted
Context.WithFocus is the single largest allocation site in the engine —
around a quarter of everything a render allocates, because a path step runs
once per node. Reusing one focus context across a step loop looked like an
obvious win. Measured: 4,963,596 → 4,964,187 bytes per render. Nothing. Go’s
escape analysis was already handling it, and the aliasing risk that reuse
introduces bought exactly zero, so it was reverted. The comment in
xpath/context.go records the numbers so nobody repeats the experiment.
Benchmarks
The full comparison with other engines, cold and warm, across nine workloads,
is in docs/benchmark.md, measured with
go-xml-bench and re-run after the
performance work in docs/profiling.md. The figures below are the in-process
Go benchmarks; they and the Saxon table after them were measured in August 2026, before that
work, on a UBL and an Oman corpus that are not in this repository, and have not
been re-run since. benchmark.md has the current figures.
Apple M3 Pro, Go 1.26, -benchtime=200x, median of five runs. These are the
two production workloads, not microbenchmarks. Wall-clock figures vary about
±15% run to run on a laptop, so they are rounded; the allocation counts are
stable to three significant figures and are the more useful number.
| benchmark |
time |
allocated |
allocs |
UBLRender — 100 KB stylesheet, 67 match templates → HTML |
~2.6 ms |
4.96 MB |
67,850 |
OmanValidate — 87-template Schematron → SVRL |
~1.05 ms |
1.66 MB |
21,703 |
CompileUBL — one-time stylesheet compilation |
~0.90 ms |
1.36 MB |
17,578 |
ParseInvoice — XML parse, 61 MB/s |
~0.15 ms |
0.16 MB |
2,404 |
CompileUBL is the cost Transform amortises: compile once, transform many.
Reproduce with go test ./xslt/ -bench=. -benchtime=200x (requires a
testdata/ corpus — see How this was tested).
UBLRender is a 100 KB, 67-template stylesheet rendering an invoice to HTML.
OmanValidate is an 87-template Schematron rule set producing an SVRL report.
CompileUBL is the one-time cost that Transform then amortises across every
document.
Against Saxon-HE 12.4
Validating the same document repeatedly, one process handling the whole batch:
| documents |
go-xml |
Saxon-HE 12.4 |
| 4 |
0.04 s |
0.81 s |
| 100 |
0.16 s |
0.81 s |
| 1000 |
1.38 s |
2.01 s |
Read this carefully rather than as a win. Saxon’s cost is almost entirely
fixed: 4 documents and 100 documents both take 0.81 s, because that is JVM
startup plus stylesheet compilation. Its marginal cost is about 1.2 ms per
document against go-xml’s 1.3 ms — so on a hot loop the JIT is slightly ahead,
and at a large enough batch Saxon would catch up and pass.
Where go-xml is unambiguously better is anything that pays startup often: a CLI
invocation (0.26 s versus 0.67 s cold), a short-lived container, a per-request
validator. Where it is not better is a long-running process transforming
millions of documents. Neither engine is “fast”; they are fast at different
shapes of work.
Security defaults
Every remote-reference mechanism is off unless you turn it on.
-
DOCTYPE is rejected by the parser unless ParseOptions.AllowDOCTYPE is
set. It is the entry point for both XXE and entity-expansion blowup. With
it on, entity expansion stays bounded (ParseOptions.MaxEntityDepth,
MaxEntityBytes, MaxTotalEntityBytes, MaxEntities) and so are external
reads (MaxExternalFetches, MaxExternalFetchBytes, MaxExternalDepth);
zero keeps each default, see docs/options.md.
xslt.FileResolver has the same seven fields; as a transform’s Documents
they also bind fn:parse-xml and a nested fn:transform’s
stylesheet-text.
-
fn:doc and fn:document fail closed as a library. With no
DocumentResolver configured, every URI is refused. The CLI is not
fail-closed in the same sense: it always configures a resolver rooted at the
stylesheet’s own directory, because a rule set that includes a sibling module
is the normal case. That root is shared with doc(), so a stylesheet can
read any file beside it, not only include one — keep stylesheets in a
directory of their own if that matters. Everything outside stays refused.
xslt.FileResolver confines reads to directories you name and refuses every
non-file scheme; there is no network option. Confinement is enforced by
os.Root at the moment of opening rather than by resolving a path and
checking it first, so a symlink swapped between the check and the open cannot
escape — the older resolve-then-check design had that gap. Every rooted
resolver works this way: xslt, xsd, dtd and the relaxng resolver in
cmd/go-xml, which the other three joined on 2026-09-10. Each read is
bounded by FileResolver.MaxBytes, 64 MB by default, and a larger file is
refused rather than truncated.
FileResolver.OpenDocument, its xslt.StreamingDocumentResolver method,
opens through the same os.Root; a host resolver that implements that
interface has a streamable xsl:source-document stream its documents (see
docs/options.md).
fn:transform’s stylesheet-location and source-location read through
the same resolver, so a nested transformation reaches nothing fn:doc
could not — from a stylesheet, and from an XQuery query or xpath.Eval
caller in a program that links xslt, where it is the caller’s
Env.Docs.
-
xsl:include and xsl:import fail closed the same way, via
CompileOptions.Resolver.
-
XInclude is off unless a caller runs xdm.ProcessXInclude explicitly.
It is a document-level pass rather than a parsing option — XInclude 1.0 §4
defines it as a transformation from one infoset to another — and it reads
only what an xdm.IncludeResolver hands it. xslt.FileResolver implements
that through the same resolvePath that gates fn:doc, xsl:include
and external entities, so an inclusion is confined to the named roots on
exactly the same terms: no non-file scheme, confinement enforced at the
open by os.Root, the same per-file byte limit, nothing outside the roots. This matters more here than
elsewhere, because with XInclude it is the source document — the party the
threat model already treats as hostile — that names what to read. The CLI
exposes it as -xinclude. A pass reads at most 200 resources nested at most
40 deep, which XIncludeOptions.MaxFetches and MaxDepth change.
-
xs:import and xs:include fail closed, via xsd.Options.Resolver.
The default reads a schema beside the one it was given and refuses a
remote URL outright; xsdnet.HTTPResolver is how you opt in to the network.
go-xml validate is confined on the same terms for -xsd and -rng: to
-root when given, and otherwise to the schema’s own directory, as the
transform is to its stylesheet’s.
go-xml xquery confines import module ... at and doc() to the query’s
own directory plus -allow-dir, as the transform does its stylesheet.
Since schemas name their imports as absolute URLs — the XSLT 3.0 schema
imports the XSD 1.1 schema for schemas from w3.org — the usual answer is
not to fetch them but to answer from a catalog:
r := xsd.NewCatalogResolver()
err := r.AddFromFS(os.DirFS("schemas"), xsd.W3CEntries())
CatalogResolver matches a document by namespace and by every
schemaLocation spelling it is referred to by, so one entry answers the
TR/ URL, the 2001/ URL, a bare relative path and a location-less
xs:import alike. A reference to something not in the table is an error
rather than a request; with a fallback resolver set, a local file a schema
names (its own xml.xsd, say) is read rather than shadowed. The companion
module w3cschemas ships the W3C documents
themselves — separate because they are under W3C rather than MIT terms —
and its schema for schemas is the XSD 1.1 one, so it loads under
xsd.Version11. From the command line, -catalog DIR on validate,
the transform and xquery does the same from a directory holding those
files.
-
Nesting and recursion are bounded — parse depth, XPath recursion and
template recursion each have a limit that produces an error rather than a
stack overflow.
-
Memory is bounded too. Depth bounds the stack and -timeout bounds the
clock, but neither bounds allocation: sum(1 to 9999999) is one shallow,
fast expression that materialised nine million values and peaked at 1.8 GB
of resident memory. A per-evaluation item budget now refuses it. The budget
resets for each expression, so a stylesheet evaluating a legitimate range
once per node of a large document is unaffected — that distinction is the
whole point, and it is tested.
-
Cancellation works. Transform takes a context.Context and checks it
at every loop boundary, so a pathological stylesheet is interruptible.
-
xsl:result-document never writes to disk. Secondary documents are
returned to the caller on Result.Secondary; a transform that can create
files anywhere the process can write is a decision the caller should make.
The CLI opts in with -result-dir and refuses any href resolving outside
it, symlinks included. An xsl:result-document with no href names no file
at all: section 24.3 leaves the current output URI at the base output URI, so
it is written to the principal output, and needs no flag. The CLI sets that
base output URI from where the output actually goes — the -o file, the
-result-dir directory, or the working directory, a directory being spelled
with a trailing slash — so fn:current-output-uri() reports the destination.
The library still defaults to none, since it never writes files; section 19.1
makes the choice implementation-defined and permits it to be absent.
The CLI mirrors these: -allow-dir opens document access, -allow-doctype
opens the parser, and -timeout bounds the transform. All three are off or
conservative by default.
Treat a stylesheet as code, not as data. It can read any file inside the
permitted roots, write anywhere under -result-dir, and spend the whole
-timeout doing it. The boundaries are enforced and tested — traversal,
symlinks into and out of the roots, absolute paths, and non-file schemes are
all refused, and TestResolverContainmentAttacks probes them the way an
attacker would — but inside those boundaries a stylesheet is a program you are
choosing to run.
One consequence worth stating plainly: engine-internal state is bound to
variables in a private namespace, and a stylesheet that names that namespace
can reach those values. Doing so used to panic the process, which for an
embedding server is a denial of service written in stylesheet text; every such
path now answers or errors instead. TestInternalStateIsNotReachableAsAPanic
covers twenty-two of them.
What is implemented
Coverage was established by auditing against the spec’s own inventories rather
than by recollection, across all three layers: the 7 XDM node kinds and the 22
instantiable XML Schema primitive types, all 58 XPath 2.0 grammar productions,
all 49 XSLT 2.0 elements with their behavioural attributes, and the 113
required fn: functions — checked at all 153 of their name/arity signatures,
since a call resolves against both and a function can be present at one arity
and missing at another.
XDM. All seven node kinds; the numeric tower with exact xs:decimal; the
date, time and duration types; and the five Gregorian types (gYear,
gYearMonth, gMonth, gMonthDay, gDay), which support equality but not
ordering — without a year, “is --01-15 before --02-01” has no answer that
holds for every year. xs:NOTATION is the one primitive not present: it cannot
be instantiated directly and exists only as a DTD attribute type.
XPath 2.0. All thirteen axes; every node and kind test; the full precedence
ladder; value, general and node comparisons; for, if, some/every;
instance of, cast, castable, treat; sequence operators; and the
complete required function library — strings, sequences, numerics, regular
expressions, node properties, QName accessors, URI handling, dates, durations,
format-dateTime, deep-equal, plus the xs: constructors.
Functions are registered by name and arity, since the two are what a call
resolves against. That distinction matters for the ten functions carrying an
optional trailing collation argument — compare, contains, starts-with,
ends-with, substring-before, substring-after, index-of,
distinct-values, min and max. All accept it; the codepoint collation is
honoured and any other is refused rather than silently applied as ASCII order.
xs:QName is resolved during parsing rather than at run time, because a QName
value carries the namespace URI and the prefix binding exists only in the
static context — which is also why the spec restricts its argument to a string
literal.
XSLT 2.0. Every element: apply-templates
(with modes and the built-in rules), apply-imports, next-match,
call-template, for-each, for-each-group (all four grouping modes), if,
choose, variable, param with tunnel parameters, element, attribute,
attribute-set, namespace, namespace-alias, comment,
processing-instruction, copy, copy-of, sequence, value-of, text,
sort, perform-sort, message, analyze-string, key, function,
include, import, strip-space, decimal-format, character-map,
number (all three levels — single, multiple and any — with count and
from), output (the xml, html and text methods, named as well as
unnamed), result-document, as type declarations, attribute value templates,
and the simplified literal-result-element stylesheet form.
Accumulator applicability. §18.2.2 decides which accumulators a tree has,
and reading any other is XTDE3362. For the document of the initial match
selection the set is the initial mode’s xsl:mode/@use-accumulators, whose
default is the empty list: a stylesheet reading accumulator-before over its
source document must declare <xsl:mode use-accumulators="#all"/> or name the
accumulator, as Saxon also requires. xsl:source-document and
xsl:merge-source apply their own list when they give one; a
copy-accumulators="yes" copy or a snapshot() inherits its original’s; trees
from doc(), document(), collection() and xsl:variable, and the global
context item under an initial template, have every accumulator.
XQuery 3.1. Everything the language adds on top of XPath, since the
expression half is xpath’s: direct and computed
constructors for all seven node kinds; every FLWOR clause — for, let,
where, group by, order by, count, and both the tumbling and sliding
window clauses; the prolog, with namespace, variable, function, option and
decimal-format declarations, boundary-space, construction, ordering,
empty-order, copy-namespaces and the declared context item; try/catch;
switch; typeswitch; quantified expressions; ordered/unordered; the
extension expression; and the string constructor.
The version declaration is recorded rather than discarded. A module may open
with xquery version "1.0", "3.0" or "3.1"; anything else is XQST0031,
and a module that declares nothing is compiled as 3.1. The engine implements
3.1 throughout, but the rules the versions are known to disagree on now ask
which version applies: an unprefixed declare option name is XPST0081
in 1.0 and legal from 3.0; a cast target naming a type not in scope is
XPST0051 in 1.0 and XQST0052 from 3.0; and a variable circularity running
through a function body is the static XQST0054 in 1.0 and the dynamic
XQDY0054 from 3.0. Three more follow the version the QT3 suite pairs them
on: an empty ordered {} is XPST0003 before 3.1, an unprefixed pragma name
is XPST0081 before 3.1, and a bare namespace-node() step is XPST0017 in
1.0 and XQST0134 from 3.0. See docs/xquery.md for what stays at
3.1’s reading whatever the module declares.
Both halves of import are implemented, through a store the caller fills:
import module resolves against Options.Modules and then
Options.ModuleResolver, import schema against Options.Schemas and then
Options.SchemaResolver. Both resolvers are nil by default, so nothing is
fetched and an import the store cannot answer raises XQST0059; an imported
schema is read as XSD 1.1, and an invalid one raises XQST0012. See
docs/xquery.md.
Collations. Three are implemented: codepoint, the HTML ASCII
case-insensitive collation the spec defines, and the UCA family
(http://www.w3.org/2013/collation/UCA with its strength, language and
tailoring parameters, from golang.org/x/text/collate); a host can add its own
with xpath.RegisterCollation. All are applied rather than merely validated — an xsl:sort/@collation that was
accepted and then sorted by codepoint anyway would be the silent-wrong-answer
this engine exists to avoid. Relative URIs such as collation/codepoint
resolve, because stylesheets write them that way. Anything else is refused.
Sorting and Unicode. xsl:sort supports @case-order and @lang:
Swedish orders “ä” after “z” where German orders it next to “a”, and codepoint
order gets both wrong. fn:normalize-unicode implements all four standard
forms. Both use golang.org/x/text. A @lang naming a language with no
collation data sorts as if @lang were omitted, as XSLT 3.0 §13.1.3 allows;
a value outside xs:language is an error. @collation accepts any collation
above.
Canonical XML. All three W3C algorithms — Canonical XML 1.0, Exclusive
Canonical XML 1.0 with its InclusiveNamespaces PrefixList, and Canonical XML
1.1 with its xml:base fix-up — each with and without comments, over a whole
document, a subtree, the enveloped-signature subset or any XPath-selected
node set, XML-DSig’s here() included. Two inputs the specifications leave undefined are refused rather
than guessed at: an XML 1.1 document, and a relative namespace URI. See
docs/c14n.md for how namespace nodes are handled, including
XPath filters that keep part of an element’s namespace axis, and for where it
follows the W3C i
README 内容过长,已截取前 64 KB。完整内容请前往 GitHub 仓库查看。
评论