xmlscan

package
v0.1.23 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 9 Imported by: 5 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package xmlscan is a streaming pull tokenizer for XML.

  • It does not allocate per token. Names, attribute values and text are slices of the scanner's window, valid until the next call to Next.
  • It reads through a window that is refilled as it goes, so input of any size is read in bounded memory. Text, CDATA and comments are delivered in chunks when they do not fit; a tag, a processing instruction and the document type declaration must fit, up to Options.MaxTokenBytes. Windows are pooled: Release hands one back.
  • It reads UTF-8, UTF-16 and what an XML declaration names, decoded by go-fast-core/charset (encoding.go).
  • It resolves namespace prefixes, to the URI and to small numbers the caller chooses.
  • It never reads anything but its input. General entity references other than the five predefined ones are given to Options.Resolve, and a replacement read as markup is read from memory, within a bound on nesting and on the bytes all expansions produce together.
  • By default it reads well-formed XML and stops with ErrSyntax at the first error. With Options.Recover it reads on through damaged markup the way a lenient reader does and counts each repair: an end tag that matches an element further out closes what is inside it, one that matches nothing is dropped, elements left open at the end are closed, a "<" or "&" that starts no markup is text, an attribute without a value or quotes is read as far as it goes, and elements nested deeper than Options.MaxDepth are read as part of their ancestor (their tags passed over, their text kept).
  • Comments, processing instructions and the document type declaration are tokens with Options.Markup; otherwise they are passed over, and a document type declaration is accepted only if it declares nothing (no internal subset, before the root, only one).

Index

Constants

View Source
const (
	XMLNamespace   = "http://www.w3.org/XML/1998/namespace"
	XMLNSNamespace = "http://www.w3.org/2000/xmlns/"
)

The namespaces bound to the reserved prefixes.

View Source
const (
	DefaultMaxDepth       = 512
	DefaultMaxTokenBytes  = 16 << 20
	DefaultBufferSize     = 64 << 10
	DefaultMaxAttrs       = 1024
	DefaultMaxEntityDepth = 16
	// MaxEntityName is the longest entity name looked up. A longer one is
	// not read as a reference.
	MaxEntityName = 64
	// DefaultMaxValueBytes is a bound on one decoded attribute value for
	// XML from anywhere (Options.MaxValueBytes).
	DefaultMaxValueBytes = 1 << 20
	// MaxNameKept bounds the bytes of an open element's name that are
	// kept, for its End token and for matching its end tag (two names
	// longer than this match when their kept starts and lengths do).
	// The Start token has the whole name; the End token of a longer one
	// has its first MaxNameKept bytes or fewer, cut where a character
	// starts.
	MaxNameKept = 1024
	// MaxBindingBytes bounds the prefixes and URIs of the namespace
	// declarations in scope.
	MaxBindingBytes = 16 << 20
)

Defaults for Options.

View Source
const MaxChunk = 64 << 10

MaxChunk bounds the text of one Text or Comment token read from the input: longer character data, CDATA sections and comments come in pieces, cut at white space where there is some. A consumer that puts block boundaries only between tokens then has a source offset for each.

View Source
const Poisoned = poison

Poisoned reports whether the xmlscanpoison tag is set.

Variables

View Source
var (
	ErrSyntax = errors.New("xmlscan: malformed XML")
	// ErrDTD: without Options.Markup, a document type declaration with an
	// internal subset, after the root element has begun, or a second one.
	ErrDTD = errors.New("xmlscan: a document type declaration with an internal subset, or out of place, is not accepted")
	// ErrDepth: without Options.Recover, elements nested deeper than
	// Options.MaxDepth.
	ErrDepth = errors.New("xmlscan: elements nested too deeply")
	// ErrTokenTooLarge: a tag, a processing instruction or the document
	// type declaration is larger than Options.MaxTokenBytes.
	ErrTokenTooLarge = errors.New("xmlscan: a tag is larger than the token limit")
	// ErrEncoding: an XML declaration names an encoding that is not
	// decoded.
	ErrEncoding = errors.New("xmlscan: unsupported character encoding")
)

Errors reported by Err. Syntax errors wrap ErrSyntax and carry the byte offset.

View Source
var ErrReferenceTooLarge = fmt.Errorf("%w: a character reference", ErrTokenTooLarge)

ErrReferenceTooLarge is the ErrTokenTooLarge of a character reference longer than the token limit (leading zeros); errors.Is matches both.

Functions

func UTF8

func UTF8(r io.Reader) (utf8 io.Reader, converted bool, err error)

UTF8 returns the input as the scanner reads it: converted to UTF-8 from the encoding its byte order mark or declaration names, without the mark. converted reports that it was not UTF-8. The error is ErrEncoding, for an encoding the scanner does not read, or the reader's.

Types

type Binding

type Binding struct{ Prefix, URI string }

Binding declares a namespace: Prefix is "" for the default namespace.

type Kind

type Kind uint8

Kind is the type of a token.

const (
	// EOF means the input ended or an error occurred. Err tells which.
	EOF Kind = iota
	// Start is a start tag. An empty-element tag (<a/>) gives Start and
	// then End.
	Start
	// End is an end tag.
	End
	// Text is character data or a CDATA section. One run of text in the
	// source may arrive as several Text tokens.
	Text
	// Comment is the content of a comment. A long comment arrives as
	// several Comment tokens; Final reports the last one.
	Comment
	// PI is a processing instruction: Target and Text.
	PI
	// Doctype is a document type declaration. Text is what lies between
	// "<!DOCTYPE" and the final ">".
	Doctype
)

type Options

type Options struct {
	// Spaces maps namespace URIs to the caller's numbers. It is only read.
	Spaces map[string]Space
	// MaxDepth bounds element nesting. Deeper is ErrDepth, or, with
	// Recover, an element read as part of its ancestor and counted in
	// Stats.Flattened. Zero means DefaultMaxDepth.
	MaxDepth int
	// MaxTokenBytes bounds the size of one tag, processing instruction or
	// document type declaration. Zero means DefaultMaxTokenBytes.
	MaxTokenBytes int
	// MaxAttrs bounds the attributes kept from one tag; the rest are
	// counted in Stats.AttrsCut. Zero means DefaultMaxAttrs.
	MaxAttrs int
	// BufferSize is the initial window size when reading from an
	// io.Reader. Zero means DefaultBufferSize.
	BufferSize int
	// Resolve decides general entity references other than the
	// predefined ones. Nil keeps them as written, counted as repairs.
	Resolve Resolver
	// MaxEntityDepth bounds how deeply replacements read as markup nest.
	// Zero means DefaultMaxEntityDepth.
	MaxEntityDepth int
	// ExpansionLimit bounds the bytes of replacement text read in place
	// of references, all expansions together. Zero means no expansion at
	// all; negative means no limit.
	ExpansionLimit int64
	// BaseOffset is the offset of the first byte read, added to every
	// offset the scanner reports.
	BaseOffset int64
	// MaxValueBytes bounds one decoded attribute value; a longer one is
	// cut and counted in Stats.ValuesCut. Zero means no bound but
	// MaxTokenBytes (DefaultMaxValueBytes is a bound for XML from
	// anywhere).
	MaxValueBytes int
	// Interrupt, if set, is called every 1,024 constructs Next passes
	// over without making a token; an error it returns ends the scan.
	Interrupt func() error
	// Recover makes the scanner read on through damaged markup (see the
	// package documentation), counting each repair in Stats.Repairs.
	// Without it the first error ends the scan with ErrSyntax.
	Recover bool
	// Markup makes comments, processing instructions and the document
	// type declaration tokens (Comment, PI, Doctype). Without it they are
	// passed over, and a document type declaration is accepted only if it
	// declares nothing.
	Markup bool
	// Decoded says the input is UTF-8 already, whatever its XML
	// declaration says: it was decoded on the way in.
	Decoded bool
	// Spans makes Span report where each token is in the input. Without
	// it, Span reports it only for Comment, PI and Doctype tokens and
	// markup kept as text.
	Spans bool
	// Bindings are namespace declarations in scope before the input's
	// first element, as if an element around it had made them. They are
	// for XML read out of a larger document, such as a part of a Flat OPC
	// package, which may use a prefix that an ancestor in that document
	// declares.
	Bindings []Binding
}

Options configures a Scanner. The zero value is usable.

type Resolution

type Resolution uint8

Resolution says how a general entity reference is read.

const (
	// Keep keeps the reference in the text as written.
	Keep Resolution = iota
	// Insert puts the replacement in the text as it is, as characters.
	Insert
	// Expand reads the replacement in place of the reference, as markup.
	Expand
)

type Resolver

type Resolver func(name []byte) (repl []byte, how Resolution)

Resolver decides how a general entity reference other than the five predefined ones is read, and gives its replacement.

type Scanner

type Scanner struct {

	// Stats counts repairs, cuts and expansion.
	Stats Stats
	// contains filtered or unexported fields
}

Scanner reads XML tokens. Create one with New or NewBytes, or reuse one with Reset or ResetBytes, which keeps its buffers.

func New

func New(r io.Reader, opts *Options) *Scanner

New returns a Scanner reading from r.

func NewBytes

func NewBytes(data []byte, opts *Options) *Scanner

NewBytes returns a Scanner reading from data, which it does not modify or copy.

func (*Scanner) Abort

func (s *Scanner) Abort(err error)

Abort ends the scan: from now on Next returns EOF and Err returns err, unless the scan had failed already.

func (*Scanner) AppendText

func (s *Scanner) AppendText(dst []byte) []byte

AppendText reads to the end of the element whose Start token is current and appends all character data inside it, at any depth, to dst.

func (*Scanner) Attr

func (s *Scanner) Attr(space Space, local string) ([]byte, bool)

Attr returns the value of the attribute with the given namespace and local name on the current Start token. An attribute written without a prefix has namespace NoSpace. The value has references decoded, is valid UTF-8 as Text is, and is good until the next call to Next.

func (*Scanner) AttrAny

func (s *Scanner) AttrAny(local string) ([]byte, bool)

AttrAny returns the value of the first attribute with the given local name, whatever its namespace. It is for attributes that producers write both with and without a prefix.

func (*Scanner) AttrAt

func (s *Scanner) AttrAt(i int) (space Space, local, value []byte)

AttrAt returns the i-th attribute of the current Start token: its namespace, local name and decoded value. A namespace declaration's namespace is that of the prefix "xmlns" (SpaceUnknown), or NoSpace for the default namespace's.

func (*Scanner) AttrNameAt

func (s *Scanner) AttrNameAt(i int) []byte

AttrNameAt returns the qualified name of the i-th attribute of the current Start token as written in the source, prefix included. It is valid UTF-8 as Name is.

func (*Scanner) AttrURI

func (s *Scanner) AttrURI(uri, local string) ([]byte, bool)

AttrURI returns the value of the attribute with the given namespace URI (empty for none) and local name on the current Start token.

func (*Scanner) AttrURIAt

func (s *Scanner) AttrURIAt(i int) (uri, local, value []byte)

AttrURIAt returns the i-th attribute of the current Start token: its namespace URI (empty for none), local name and decoded value. A namespace declaration has the xmlns namespace.

func (*Scanner) Depth

func (s *Scanner) Depth() int

Depth returns the number of open elements. After a Start token it includes that element; after an End token it does not.

func (*Scanner) Err

func (s *Scanner) Err() error

Err returns the error that ended the scan, or nil at a clean end of input.

func (*Scanner) Final

func (s *Scanner) Final() bool

Final reports whether the current Comment token is the last piece of its comment.

func (*Scanner) InEntity

func (s *Scanner) InEntity() bool

InEntity reports whether the current token comes from the replacement of an entity reference.

func (*Scanner) Is

func (s *Scanner) Is(space Space, local string) bool

Is reports whether the current Start or End token is the element with the given namespace and local name.

func (*Scanner) Kind

func (s *Scanner) Kind() Kind

Kind returns the kind of the current token, as last returned by Next.

func (*Scanner) Local

func (s *Scanner) Local() []byte

Local returns the local name of the current Start or End token. At an End token it is cut as Name is.

func (*Scanner) Name

func (s *Scanner) Name() []byte

Name returns the qualified name of the current Start or End token as it is written in the source, prefix included. It is valid UTF-8: a byte that is not part of a character is U+FFFD, counted in Stats.InvalidUTF8 at the Start token. An end tag is matched to its start tag by the name so mended, so two names that differ only in such bytes match; a prefix is bound by its bytes as written. A Start token has the whole name. An End token has what was kept of its start tag's name: all of it, or the first MaxNameKept bytes or fewer of a longer one (Stats.NamesCut).

func (*Scanner) Next

func (s *Scanner) Next() Kind

Next advances to the next token and returns its kind.

func (*Scanner) NumAttr

func (s *Scanner) NumAttr() int

NumAttr returns the number of attributes kept on the current Start token, namespace declarations included.

func (*Scanner) Offset

func (s *Scanner) Offset() int64

Offset returns the byte offset in the input of the next unread byte. While the replacement of an entity reference is read, it is the offset of the reference.

func (*Scanner) Release

func (s *Scanner) Release()

Release hands the scanner's window back to be reused, and leaves the scanner at the end of its stream until it is Reset. What it read is a view of the window, so nothing of it may be held after: that holds already, since the window slides over the stream as it is read.

func (*Scanner) Reset

func (s *Scanner) Reset(r io.Reader, opts *Options)

Reset makes the scanner read from r, keeping its buffers.

func (*Scanner) ResetBytes

func (s *Scanner) ResetBytes(data []byte, opts *Options)

ResetBytes makes the scanner read from data, keeping its buffers.

func (*Scanner) SetResolver

func (s *Scanner) SetResolver(r Resolver)

SetResolver replaces Options.Resolve, as a reader does once it has read the document type declaration.

func (*Scanner) Skip

func (s *Scanner) Skip() bool

Skip reads past the end of the element whose Start token is current. It reports false if the input ended first.

func (*Scanner) Space

func (s *Scanner) Space() Space

Space returns the namespace of the current Start or End token.

func (*Scanner) Span

func (s *Scanner) Span() (start, end int64)

Span returns the byte offsets in the input where the current token starts and ends, with Options.Spans. A token read from the replacement of an entity reference has the offsets of the outermost reference.

func (*Scanner) Target

func (s *Scanner) Target() []byte

Target returns the target of the current PI token, valid UTF-8 as Name is.

func (*Scanner) Text

func (s *Scanner) Text() []byte

Text returns the content of the current Text, Comment, PI or Doctype token. Text has references decoded; all have line ends normalized to "\n", except Doctype, which is as written. It is valid UTF-8: a byte of the input that is not part of a character is U+FFFD, counted in Stats.InvalidUTF8.

func (*Scanner) URI

func (s *Scanner) URI() []byte

URI returns the namespace URI of the current Start or End token, empty for none or an undeclared prefix.

type Space

type Space uint16

Space identifies an XML namespace. Callers number the namespaces they care about from FirstSpace and pass the numbering in Options.Spaces.

const (
	// NoSpace is the absence of a namespace: an attribute without a
	// prefix, or an element where no default namespace is in force.
	NoSpace Space = iota
	// SpaceXML is the namespace of the reserved "xml" prefix (xml:space).
	SpaceXML
	// SpaceUnknown is any namespace not listed in Options.Spaces, and any
	// prefix that was never declared.
	SpaceUnknown
	// FirstSpace is the first number available to callers.
	FirstSpace
)

type Stats

type Stats struct {
	// Repairs counts the places where damaged markup was read leniently,
	// and references kept as written (an unknown entity, a character
	// reference without its semicolon).
	Repairs int
	// Flattened counts elements nested deeper than Options.MaxDepth.
	Flattened int
	// AttrsCut counts attributes past Options.MaxAttrs.
	AttrsCut int
	// EntitiesCut counts references kept as written because expanding
	// them would pass Options.MaxEntityDepth or Options.ExpansionLimit.
	EntitiesCut int
	// EntitiesRecursive counts references to an entity inside its own
	// replacement, kept as written.
	EntitiesRecursive int
	// Expanded is the bytes of replacement text read in place of
	// references.
	Expanded int64
	// ValuesCut counts attribute values cut to Options.MaxValueBytes, or
	// to what is left of MaxTokenBytes for all the values of one tag, as
	// they are read.
	ValuesCut int
	// NamesCut counts element names longer than MaxNameKept, of which
	// only the start is kept for the End token.
	NamesCut int
	// BindingsCut counts namespace declarations not read because those
	// in scope already hold MaxBindingBytes.
	BindingsCut int
	// CharRefsReplaced counts character references to no character XML
	// allows anywhere (&#0;, a surrogate, a number past U+10FFFF), each
	// read as U+FFFD. Each is counted in Repairs too.
	CharRefsReplaced int
	// InvalidUTF8 counts the bytes of text, attribute values and names
	// read that are not part of a UTF-8 character, each read as U+FFFD
	// (input that is UTF-8 is handed on as it is, and need not be valid).
	// A name is counted once: an element's at its Start token, not again
	// at its End.
	InvalidUTF8 int
}

Stats counts what the scanner did besides reading well-formed input.

Jump to

Keyboard shortcuts

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