xmlscan

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 6 Imported by: 0 modules, 0 packages

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.
  • 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.
  • It recovers from 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.
  • Elements nested deeper than Options.MaxDepth are read as part of their ancestor: their tags are passed over, their text is kept.

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 bounds one decoded attribute value.
	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).
	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.

Variables

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.

View Source
var ErrTokenTooLarge = errors.New("xmlscan: a tag is larger than the token limit")

ErrTokenTooLarge is the error when a tag, a processing instruction or the document type declaration is larger than Options.MaxTokenBytes.

Functions

This section is empty.

Types

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: an element deeper is 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 DefaultMaxValueBytes.
	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
}

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.

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) Attr

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

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

func (*Scanner) AttrAt

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

AttrAt 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) 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.

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) 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.

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.

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) 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) 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. 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.

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.

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.
	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.
	ValuesCut int
	// NamesCut counts element names longer than MaxNameKept, of which
	// only the start is kept.
	NamesCut int
	// BindingsCut counts namespace declarations not read because those
	// in scope already hold MaxBindingBytes.
	BindingsCut 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