sax

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 11 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 sax provides a simplified SAX-style wrapper for parsing HTML/XHTML/XML.

It also provides an encoding/xml.TokenReader adapter (TokenReader) so it can be used with the stdlib encoding/xml.Decoder (see encoding/xml.NewTokenDecoder) or other libraries. It supports all htmlstream reader modes (htmlstream.Universal, htmlstream.HTML, htmlstream.XML), and behaves accordingly. It also supports reading a partial fragment (see Reader.SetFragment).

A Reader (see NewReader) reads the tokens of an htmlstream.Reader and delivers them as events: Reader.Next advances to the next Event and Reader.Event returns it, or Reader.All iterates over the events, and Reader.Walk calls the functions of a Handler for them. Afterwards, Reader.Err returns the error that stopped it, if any. Unless an error stops the Reader, every StartElement event is followed by exactly one EndElement event with the same Name, including for void and self-closed elements, and Reader.Path returns the names of the open elements. Text is decoded, and text split into several tokens and adjacent CDATA sections are delivered as one Text event, up to a maximum size (see Reader.SetMaxText). Reader.Skip skips the contents of an element, and Reader.ReadText reads its text.

It is simpler to use than the htmlstream.Reader, which is more efficient and better for edits which must leave the rest of the input unchanged (see htmlstream.Transformer): the events don't keep the markup as written, and the Reader drops some tags to keep the elements balanced (see Warnings and strict mode). It doesn't check that XML documents are well-formed, even in strict mode: references to entities other than the named character references of HTML are left as they are (see htmlstream.XML), and duplicate attributes, unbound namespace prefixes, several root elements and text outside the root element aren't errors (see github.com/pgaskin/htmlstream/xmlutil.CheckWellFormed for a separate check).

Elements

The elements are those of the element model of the htmlstream.Reader (see Element model in the htmlstream package documentation): end tags are implied where HTML parsers imply them, and elements are closed by the end of the input, by an implied EndElement event (see Event.Implied). Element names are as parsers give them: in HTML (see htmlstream.Token.HTMLRules), local names are lowercase, except for SVG elements with mixed-case names (see htmlstream.AdjustSVGTagName), and the namespace is that of HTML parsers, and so is the local name of an element with a prefix under HTML rules: the qualified name, lowercase (e.g., o:p, see htmlstream.Token.AppendLocalName). The local name of an element with a namespace prefix not bound to a namespace is the qualified name, with the prefix (see Name).

In htmlstream.HTML mode, and in documents read like in HTML mode in htmlstream.Universal mode, the implied html, head and body elements (see the tree construction stage of the HTML Standard) are delivered as StartElement and EndElement events without tags in the input (see Event.Implied), where htmlutil.Document reports them. Like HTML parsers, the Reader keeps the html and body elements open after their end tags (see the after body insertion mode), so the content after them is in the body, and their EndElement events are delivered at the end of the input. This also applies when the Reader starts in the middle of the input, but not to fragments. The paths of the elements match the document tree of HTML parsers, with these differences:

  • The differences between the element model of the htmlstream.Reader and the tree construction stage of HTML parsers, e.g., there is no adoption agency algorithm, no implied tbody element and no foster parenting, template contents are read like other content, and a body or html end tag closes the elements open in the body.
  • Comments after a body or html end tag, before any other content except whitespace, are delivered in the elements open there, in the body. HTML parsers put them after the body element, or after the html element once an html end tag was read.
  • Head content after the end of the head (e.g., a meta element) stays where it is, outside the head. HTML parsers move it into the head.
  • Whitespace before the html element and before the head is delivered, while HTML parsers drop it.
  • Misplaced html, head and body start tags are dropped (see Warnings and strict mode). HTML parsers add the attributes of html and body start tags to the element.
  • Frameset documents aren't recognized: a frameset element after the head is put in a body element.
  • With scripting disabled (the default, see htmlstream.Reader.SetScripting), a noscript element in an implied head contains the content following it, which HTML parsers put in the body, and the head ends after it.

The html, head and body elements are only synthesized if the htmlstream.Reader is in HTML or Universal mode and hasn't read any token when the Reader starts, unless the input is read as a fragment (see Reader.SetFragment). A Reader can also start in the middle of the input, e.g., after htmlstream.Reader.Find: its path then starts with the elements open in the htmlstream.Reader (see htmlstream.Reader.Stack), its first event is that of the current token, and the EndElement events of the elements open at the start have no StartElement events. The end tags of html and body elements implied before the start aren't for elements open in the htmlstream.Reader, so they are stray, and are dropped with a Warning event like other stray end tags. Under XML rules (see htmlstream.Token.HTMLRules), and for fragments, html and body elements are closed by their end tags, as in the htmlstream.Reader.

Like HTML parsers, the Reader drops a newline directly after the start tag of a pre, listing or textarea element following HTML rules (see the in body insertion mode), but not one at the start of a CDATA section there (read with XML syntax), which HTML parsers read as a bogus comment, and XML parsers keep. It drops a byte order mark at the start of the input, like HTML and XML parsers (see decode in the Encoding Standard, and Autodetection of Character Encodings in XML 1.0). Text events keep NUL as the tokenizer emits it in text (see htmlstream.Token.AppendText), while HTML parsers drop it in HTML content and replace it with U+FFFD in SVG and MathML content.

With XML syntax (with htmlstream.Reader.SetXMLSyntax in HTML mode, and in documents read like in HTML mode in Universal mode), the contents of title, textarea, script and style elements are text up to their end tag, as in HTML parsers, so a CDATA section in them is text, markers included (e.g., <title><![CDATA[a<b]]></title> is the text "<![CDATA[a<b]]>"), with character references decoded in title and textarea. XML parsers read it as a CDATA section, without the markers, and the polyglot package removes a CDATA section around all of the contents. htmlutil.CutCDATAWrapper with htmlutil.CDATABare removes such a section from the text.

Warnings and strict mode

To keep the elements balanced, the Reader drops some tags, and delivers a Warning event instead: for stray end tags (see htmlstream.Token.Stray) other than those of the implied or kept-open head, body and html elements, and for ignored or misplaced html, head and body start tags (their end tags are dropped too, and the contents are kept). HTML parsers ignore these start tags, except that they add the attributes of an html or body start tag to the existing element. They ignore most stray end tags too, but read a stray </p> as an empty p element and a stray </br> as a br element. Under HTML rules, and before the rules are chosen in Universal mode, the Reader also drops, like HTML parsers, start tags cut off by the end of the input (see htmlstream.Token.Incomplete), and doctypes in a fragment or after another doctype or content other than whitespace, comments and processing instructions (since the Reader started). Under XML rules, these are delivered, as the Reader doesn't check that XML documents are well-formed: a start tag cut off by the end of the input is an element without contents. The text of the event says what was dropped. A Warning event also follows the Text event of a CDATA section in HTML content (with htmlstream.Reader.SetXMLSyntax in HTML mode, and in documents read like in HTML mode in Universal mode) which reaches the end of the input, as its end is missing: its text is the rest of the input, while HTML parsers read a bogus comment ending at the first ">". Its position is the end of the input.

In strict mode (see Reader.SetStrict), a SyntaxError event is delivered instead of a Warning event, and for every structurally unsound token (see htmlstream.Token.Unsound). It stops the Reader: the next call to Next returns false, and Err returns the error, an *htmlstream.SyntaxError.

Elements nested past the stack limits of the htmlstream.Reader (see htmlstream.Token.Untracked) have no name in the element model, so the Reader can't deliver them as balanced elements. Instead, their tokens, from their start tag to their end tag, are delivered as Untracked events, and their text isn't lost. The implied html, head and body elements (see Elements) aren't delivered in untracked content: an untracked html element has no implied head and body elements, also for the content after its end tag, and in an untracked head element, or untracked head content (e.g., a noscript element in an implied head), the head ends and the body starts after the untracked element, as when the head content is tracked.

Limits

Like the htmlstream.Reader, a Reader reads input of any size with bounded memory: the text of a Text or Comment event is limited in size (see Reader.SetMaxText), longer text being delivered in several events (see Event.Partial), and that of other events is limited by the maximum token size of the htmlstream.Reader (see htmlstream.Reader.SetMaxTokenSize); the path has at most the elements tracked by the htmlstream.Reader (see htmlstream.Reader.SetMaxDepth) and the html, head and body elements; and at most 4096 names of up to 64 bytes are interned (other names are allocated for each event).

To merge text, the Reader reads the token after it before delivering it, and it keeps track of all the tokens: after the first call to Next, the htmlstream.Reader must not be advanced by other means (e.g., by its own Next or Skip method) while the Reader is used. If the current event has a token (see Event.Token), it is the current token of the htmlstream.Reader, which can then be read further without the Reader (e.g., to decode the elements found by htmlstream.Reader.Find one at a time, with a new Reader for each). A Reader can't be used with a Transformer's Reader (see htmlstream.Transformer.Reader), since edits apply to the current token of the htmlstream.Reader, which isn't always the one of the current event.

Example

Extract the metadata and manifest of an EPUB package document.

package main

import (
	"fmt"
	"strings"

	"github.com/pgaskin/htmlstream"
	"github.com/pgaskin/htmlstream/sax"
)

// opf is an EPUB package document with an undeclared entity (&mdash;), an
// unescaped ampersand and an item without "/>", which encoding/xml rejects.
const opf = `<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="uid">
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:identifier id="uid">urn:uuid:1234</dc:identifier>
    <dc:title>Pride &amp; Prejudice &mdash; Vol. 1</dc:title>
    <dc:creator>Jane Austen & Co.</dc:creator>
    <meta property="dcterms:modified">2020-01-01T00:00:00Z</meta>
  </metadata>
  <manifest>
    <item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>
    <item id="c1" href="c1.xhtml" media-type="application/xhtml+xml"></item>
    <item id="css" href="style.css" media-type="text/css">
  </manifest>
  <spine><itemref idref="c1"/></spine>
</package>`

const (
	nsOPF = "http://www.idpf.org/2007/opf"
	nsDC  = "http://purl.org/dc/elements/1.1/"
)

func main() {
	r := htmlstream.NewReader(strings.NewReader(opf))
	r.SetMode(htmlstream.XML)
	s := sax.NewReader(r)
	for ev := range s.All() {
		if ev.Kind != sax.StartElement {
			continue
		}
		switch ev.Name {
		case sax.Name{Space: nsDC, Local: "title"}, sax.Name{Space: nsDC, Local: "creator"}:
			name := ev.Name.Local
			text, _ := s.ReadText(nil, 1024)
			fmt.Printf("%s: %s\n", name, text)
		case sax.Name{Space: nsOPF, Local: "item"}:
			path := s.Path()
			if len(path) < 2 || path[len(path)-2] != (sax.Name{Space: nsOPF, Local: "manifest"}) {
				break
			}
			id, _ := ev.Attr("id")
			href, _ := ev.Attr("href")
			fmt.Printf("item %s: %s\n", id, href)
		}
	}
	if err := s.Err(); err != nil {
		fmt.Println(err)
	}
}
Output:
title: Pride & Prejudice — Vol. 1
creator: Jane Austen & Co.
item nav: nav.xhtml
item c1: c1.xhtml
item css: style.css

Index

Examples

Constants

View Source
const DefaultMaxText = 1 << 20

DefaultMaxText is the default maximum size of the text of an event (see Reader.SetMaxText), 1 MiB.

Variables

View Source
var ErrUntracked = errors.New("sax: can't decode element nested past the stack limits (MaxDepth or MaxStackBytes)")

ErrUntracked is returned by TokenReader.Token at the Untracked event of a start or end tag, since the tag can't be delivered as an element (the Reader's current event is that event).

View Source
var SkipElement = errors.New("skip this element")

SkipElement is used as a return value from the functions of a Handler to indicate that the element of the event is to be skipped (see Reader.Walk). It is not returned as an error by any function.

Functions

This section is empty.

Types

type Event

type Event struct {
	// Kind is the kind of event.
	Kind Kind

	// Name is the name of the element of a StartElement or EndElement event
	// (see [Name]), or the target of a ProcInst event (in Local, as
	// written).
	Name Name

	// Text is the text of the event:
	//   - for a Text event, the decoded text (see [htmlstream.Token.AppendText]),
	//     which is never empty;
	//   - for a Comment event, the decoded comment, which can be empty (</>,
	//     which HTML parsers ignore, gives no event, see
	//     [htmlstream.Token.Bogus]);
	//   - for a ProcInst event, the data after the target, as XML parsers
	//     read it (see [htmlstream.Token.AppendText]);
	//   - for a Doctype event, the contents of the doctype after "DOCTYPE"
	//     and the whitespace after it, as written (e.g., "html");
	//   - for a Warning or SyntaxError event, a description of the problem
	//     (e.g., "dropped stray </span>");
	//   - for an Untracked event, the text of a Text, CDATA, Comment,
	//     ProcInst or Doctype token, as for those events.
	Text []byte

	// Partial reports that the text of a Text or Comment event continues in
	// the next event, of the same kind, because it is longer than the
	// maximum text size (see [Reader.SetMaxText]), or that the token of an
	// Untracked event is continued by the token of the next one (see
	// [htmlstream.Token.Partial]), because it is longer than the chunk size
	// of the htmlstream.Reader (see [htmlstream.Reader.SetChunkSize]).
	// In strict mode, the next event can be a SyntaxError event instead.
	// Without Partial, the next event doesn't continue the text: text events
	// end at other markup (e.g., a comment), at a dropped tag, at a body or
	// html end tag, where HTML parsers start the body, and in strict mode, at
	// an unsound token.
	Partial bool

	// Implied reports that the event has no tag in the input: a StartElement
	// event for an implied html, head or body element (see Elements in the
	// package documentation), or an EndElement event for an element closed
	// without an end tag (see [htmlstream.Token.Implied]), a void or
	// self-closed element, an implied html, head or body element, or an html
	// or body element kept open after its end tag.
	Implied bool

	// Pos is the position in the input of the first token of the event. For
	// a Text or Comment event continuing a Partial one, it is that of the
	// token whose text was split. For the EndElement event of an element
	// whose start tag doesn't open one (a void or self-closed element, see
	// [htmlstream.Token.Opens]), it is that of the start tag. For other
	// implied StartElement and EndElement events, it is that of the token
	// before which it is delivered, or the end of the input. For the Warning
	// event of a CDATA section reaching the end of the input, it is the end
	// of the input.
	Pos htmlstream.Pos
	// contains filtered or unexported fields
}

Event is an event delivered by a Reader. It is only valid until the Reader advances, and its Text and token alias the Reader's buffers.

It implements htmlutil.NamedElement, so the element categories of htmlutil classify StartElement and EndElement events (e.g., htmlutil.IsBlock(ev)).

func (*Event) AppendLocalName

func (e *Event) AppendLocalName(dst []byte) []byte

AppendLocalName appends the local name of the element of a StartElement or EndElement event to dst.

func (*Event) Attr

func (e *Event) Attr(name string) (string, bool)

Attr returns the decoded value of the first attribute of a StartElement event named name (see htmlstream.Token.Attr). It allocates the value: to avoid that, use the attribute of the token (see Event.Token and htmlstream.Attr.AppendValue).

func (*Event) AttrNS

func (e *Event) AttrNS(ns, local string) (string, bool)

AttrNS returns the decoded value of the first attribute of a StartElement event with the local name local in the namespace ns (see htmlstream.Token.AttrNS). It allocates the value, like Event.Attr.

func (*Event) Blank

func (e *Event) Blank() bool

Blank reports whether the event is a Text event with only ASCII whitespace (see ascii.IsBlank).

func (*Event) NS

func (e *Event) NS() string

NS returns the namespace URI of the element of a StartElement or EndElement event, or an empty string for other events.

func (*Event) Token

func (e *Event) Token() *htmlstream.Token

Token returns the token of the event: the start tag of a StartElement event, and of the EndElement event of a void or self-closed element; the end tag (possibly implied) of other EndElement events, including the head end tag of an implied head element, which is stray for the htmlstream.Reader; the token of a ProcInst, Doctype or Untracked event; and the dropped or unsound token of a Warning or SyntaxError event. It returns nil for the StartElement and EndElement events of implied html, head and body elements and the EndElement events of html and body elements kept open after their end tags (see Event.Implied), for Text and Comment events, which can have several tokens, and for the Warning event of a CDATA section reaching the end of the input (see Warnings and strict mode in the package documentation). It is valid as long as the event.

type Handler

type Handler struct {
	StartElement func(r *Reader, ev *Event) error
	EndElement   func(r *Reader, ev *Event) error
	Text         func(r *Reader, ev *Event) error
	Comment      func(r *Reader, ev *Event) error
	ProcInst     func(r *Reader, ev *Event) error
	Doctype      func(r *Reader, ev *Event) error
	Warning      func(r *Reader, ev *Event) error
	SyntaxError  func(r *Reader, ev *Event) error
	Untracked    func(r *Reader, ev *Event) error
}

Handler holds the functions Reader.Walk calls for the events of each kind. A nil function ignores the events.

type Kind

type Kind uint8

Kind is the kind of an Event.

const (
	StartElement Kind = iota + 1 // the start of an element
	EndElement                   // the end of an element
	Text                         // text, including CDATA sections
	Comment                      // a comment
	ProcInst                     // a processing instruction
	Doctype                      // a document type declaration

	Warning     // dropped input, or a CDATA section reaching the end of the input
	SyntaxError // unsound or dropped input in strict mode
	Untracked   // a token of an element nested past the stack limits
)

func (Kind) String

func (k Kind) String() string

String returns the name of the constant for k, e.g., "StartElement".

type Name

type Name struct {
	Space string // the namespace URI (see [htmlstream.Token.NS])
	Local string // the local name, or the qualified name if the prefix isn't bound
}

Name is the name of an element, as given by parsers (see Elements in the package documentation).

If the name has a namespace prefix not bound to a namespace (e.g., in XML mode, x:a without a declaration of the prefix x), Space is empty and Local is the qualified name, with the prefix (e.g., Name{"", "x:a"}), so that the element isn't confused with one without a prefix. There are no prefixes under HTML rules (see htmlstream.Token.HTMLRules): HTML parsers read a name like x:a as a whole.

type Reader

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

Reader reads events from an htmlstream.Reader. Like the htmlstream.Reader, it isn't safe for concurrent use, and reads a single input.

func NewReader

func NewReader(r *htmlstream.Reader) *Reader

NewReader returns a Reader reading the tokens of r, starting with its current token if it has read some already (see the package documentation).

func (*Reader) All

func (s *Reader) All() iter.Seq[*Event]

All returns an iterator over the remaining events. Each event is valid until the next iteration. Check Err after iterating.

func (*Reader) Depth

func (s *Reader) Depth() int

Depth returns the number of open elements, len(Path()). Unlike htmlstream.Reader.Depth, it includes the implied html, head and body elements and doesn't include untracked elements.

func (*Reader) Err

func (s *Reader) Err() error

Err returns the first error encountered: an *htmlstream.SyntaxError in strict mode, or an error of the htmlstream.Reader. It is nil at the end of the input.

func (*Reader) Event

func (s *Reader) Event() *Event

Event returns the current event. It is valid until the next call to Next, and its Kind is zero before the first call to Next and after Next returns false.

func (*Reader) Next

func (s *Reader) Next() bool

Next advances to the next event. It returns false at the end of the input or on error.

func (*Reader) Path

func (s *Reader) Path() []Name

Path returns the names of the open elements, outermost first, including the element of the current StartElement or EndElement event. The elements of Untracked events aren't included. It is valid until the next call to Next, and must not be modified.

func (*Reader) ReadText

func (s *Reader) ReadText(dst []byte, limit int) (b []byte, truncated bool)

ReadText appends the text of the element of the current StartElement event to dst and returns the result: that of the Text events in it, and of the Text and CDATA tokens of the Untracked events in it, like the DOM's textContent. The contents of template elements in the XHTML namespace are left out, since parsers put them in a separate document fragment (see template contents and parsing XML documents), like htmlutil.TextContent does. Afterwards, the current event is the element's EndElement event, or a SyntaxError event in it in strict mode. At a Text event, it appends its text and that of the events continuing it (see Event.Partial), and the current event is the last of them, or a SyntaxError event after them in strict mode. At other events, it does nothing.

If limit is positive, at most limit bytes are appended, without splitting a UTF-8 sequence; the rest of the text is skipped and truncated is true. Check Err afterwards.

func (*Reader) SetFragment

func (s *Reader) SetFragment(v bool)

SetFragment sets whether the input is read as the contents of a body element, like HTML parsers parse a fragment with a body context element (see the fragment parsing algorithm). Under HTML rules (see htmlstream.Token.HTMLRules), the implied html, head and body elements aren't synthesized then, and html, head and body start tags are dropped, since HTML parsers ignore them in a body (see Warnings and strict mode in the package documentation). It has no effect under XML rules. It must be called before the first call to Next, and panics otherwise. The default is false.

func (*Reader) SetMaxText

func (s *Reader) SetMaxText(n int)

SetMaxText sets the maximum size of the text of a Text or Comment event (see Limits in the package documentation). Longer text is delivered in several events (see Event.Partial), split between UTF-8 sequences, except for a character longer than the maximum size, which is delivered whole. It may be called at any time. The default is DefaultMaxText, and values below 1 are treated as 1.

func (*Reader) SetStrict

func (s *Reader) SetStrict(v bool)

SetStrict sets whether dropped and structurally unsound input is a SyntaxError event, which stops the Reader (see the package documentation). The default is false. It may be called at any time, and applies to the events after the current one. It is independent of htmlstream.Reader.SetStrict, which doesn't change the events.

func (*Reader) Skip

func (s *Reader) Skip()

Skip advances to the EndElement event of the element of the current StartElement event, skipping the events in it, including Warning events. At an Untracked event of a start tag, it likewise advances to the Untracked event of the end tag of its element. It stops at an error, including a SyntaxError event in strict mode, which Err returns. At other events, Skip does nothing.

func (*Reader) Walk

func (s *Reader) Walk(h Handler) error

Walk reads the remaining events, calling the function of h for the kind of each event, until the end of the input, an error, or a function returning an error. It returns the error returned by a function, or else Err.

If a function returns SkipElement, Walk skips the element of the event: the element of a StartElement event, and the element containing other events (for an EndElement event, the parent of its element). The events in it are skipped, including Warning events, and EndElement is called next for the element. At the top level, Walk returns nil instead.

A function may advance the Reader itself (e.g., with Reader.Skip or Reader.ReadText). Walk then continues with the current event, without calling Next (so EndElement is called for an element after StartElement read its contents), and a SkipElement returned by the function has no further effect. Reading the text of a Text event with ReadText doesn't count as advancing: Walk continues after the last event read.

Example

Print the headings of an HTML document as an outline, with the text of hidden elements left out.

package main

import (
	"fmt"
	"strings"

	"github.com/pgaskin/htmlstream"
	"github.com/pgaskin/htmlstream/htmlutil"
	"github.com/pgaskin/htmlstream/sax"
)

func main() {
	r := htmlstream.NewReader(strings.NewReader(`<h1>Title</h1>
<p>Text<h2>One <script>x()</script>more</h2>
<p>Text</p></p>
<h2>Two</h2>`))
	s := sax.NewReader(r)
	var (
		in      bool
		heading strings.Builder
	)
	err := s.Walk(sax.Handler{
		StartElement: func(s *sax.Reader, ev *sax.Event) error {
			if in && htmlutil.IsHidden(ev) {
				return sax.SkipElement
			}
			if htmlutil.IsHeading(ev) {
				in = true
				heading.WriteString(strings.Repeat("  ", int(ev.Name.Local[1]-'1')))
			}
			return nil
		},
		Text: func(s *sax.Reader, ev *sax.Event) error {
			if in {
				heading.Write(ev.Text)
			}
			return nil
		},
		EndElement: func(s *sax.Reader, ev *sax.Event) error {
			if htmlutil.IsHeading(ev) {
				fmt.Println(heading.String())
				heading.Reset()
				in = false
			}
			return nil
		},
		Warning: func(s *sax.Reader, ev *sax.Event) error {
			fmt.Printf("warning at %d: %s\n", ev.Pos, ev.Text)
			return nil
		},
	})
	if err != nil {
		fmt.Println(err)
	}
}
Output:
Title
  One more
warning at 71: dropped stray </p>
  Two

type TokenReader

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

TokenReader reads the events of a Reader as the tokens of encoding/xml, implementing encoding/xml.TokenReader, so that encoding/xml.NewTokenDecoder can decode malformed XML and HTML (e.g., into structs with encoding/xml.Decoder.Decode).

Element names are those of the events (see Name), with the namespace URI in Space. Attribute names also have the namespace URI in Space (see htmlstream.Token.AttrNamespace), and the local name in Local; for an attribute with a prefix not bound to a namespace, Space is empty and Local is the qualified name (e.g., x:y), like for elements. Namespace declarations are attributes in the htmlstream.NamespaceXMLNS namespace, named xmlns for the default namespace and after the prefix otherwise, so that an encoding/xml.Decoder doesn't resolve the names again (it still replaces an empty Space with its DefaultSpace in element names, and the Space "xml" with htmlstream.NamespaceXML). Under HTML rules, attribute names are lowercase, except for the mixed-case SVG and MathML attribute names of HTML parsers (see htmlstream.AdjustSVGAttrName), and only the first of the attributes with the same name as HTML parsers read it is kept, like HTML parsers do (e.g., of xlink:href and XLINK:HREF, but not of l:href and xlink:href, even with both in the XLink namespace). An encoding/xml.Encoder writes the namespace declarations as attributes in a namespace with a generated prefix (e.g., xmlns:_xmlns="..." _xmlns:b="urn:b"), like those read by an encoding/xml.Decoder.

Text events are encoding/xml.CharData. With XML syntax, a CDATA section in a title, textarea, script or style element is text, markers included, unlike in an encoding/xml.Decoder reading the input (see the package documentation).

Warning events are left out: those for the dropped tags and doctypes, and for a CDATA section reaching the end of the input (see Warnings and strict mode in the package documentation). Some of them mark differences from HTML parsers: a stray </p> or </br>, which HTML parsers read as a p or br element, a dropped html or body start tag with attributes, which HTML parsers add to the existing element, and a CDATA section read with XML syntax reaching the end of the input, which they end at the first ">". In strict mode (see Reader.SetStrict), they are errors. The text, comments and processing instructions of Untracked events are kept, but their tags can't be delivered as elements, so Token returns ErrUntracked at the first one. A doctype is an encoding/xml.Directive starting with "DOCTYPE ".

Example

Decode a malformed EPUB package document into structs with encoding/xml.

package main

import (
	"encoding/xml"
	"fmt"
	"strings"

	"github.com/pgaskin/htmlstream"
	"github.com/pgaskin/htmlstream/sax"
)

// opf is an EPUB package document with an undeclared entity (&mdash;), an
// unescaped ampersand and an item without "/>", which encoding/xml rejects.
const opf = `<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="uid">
  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:identifier id="uid">urn:uuid:1234</dc:identifier>
    <dc:title>Pride &amp; Prejudice &mdash; Vol. 1</dc:title>
    <dc:creator>Jane Austen & Co.</dc:creator>
    <meta property="dcterms:modified">2020-01-01T00:00:00Z</meta>
  </metadata>
  <manifest>
    <item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>
    <item id="c1" href="c1.xhtml" media-type="application/xhtml+xml"></item>
    <item id="css" href="style.css" media-type="text/css">
  </manifest>
  <spine><itemref idref="c1"/></spine>
</package>`

func main() {
	var pkg struct {
		Title    string `xml:"metadata>title"`
		Manifest []struct {
			ID   string `xml:"id,attr"`
			Href string `xml:"href,attr"`
		} `xml:"manifest>item"`
	}
	r := htmlstream.NewReader(strings.NewReader(opf))
	r.SetMode(htmlstream.XML)
	d := xml.NewTokenDecoder(sax.NewTokenReader(sax.NewReader(r)))
	if err := d.Decode(&pkg); err != nil {
		fmt.Println(err)
	}
	fmt.Println(pkg.Title)
	fmt.Println(pkg.Manifest)

}
Output:
Pride & Prejudice — Vol. 1
[{nav nav.xhtml} {c1 c1.xhtml} {css style.css}]
Example (Find)

Decode the entries of a feed one at a time, without reading the whole document into memory.

package main

import (
	"encoding/xml"
	"fmt"
	"strings"

	"github.com/pgaskin/htmlstream"
	"github.com/pgaskin/htmlstream/sax"
)

func main() {
	r := htmlstream.NewReader(strings.NewReader(`<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Example</title>
  <entry><title>One &amp; two</title><link href="/1"/></entry>
  <entry><title>Three</title><link href="/3"></entry>
</feed>`))
	r.SetMode(htmlstream.XML)
	type entry struct {
		Title string `xml:"title"`
		Link  struct {
			Href string `xml:"href,attr"`
		} `xml:"link"`
	}
	for r.Find(htmlstream.TagNS("http://www.w3.org/2005/Atom", "entry")) {
		var e entry
		if err := xml.NewTokenDecoder(sax.NewTokenReader(sax.NewReader(r))).Decode(&e); err != nil {
			fmt.Println(err)
			return
		}
		fmt.Printf("%s: %s\n", e.Title, e.Link.Href)
	}
	if err := r.Err(); err != nil {
		fmt.Println(err)
	}
}
Output:
One & two: /1
Three: /3
Example (Html)

Decode an HTML document into structs with encoding/xml. The implied html, head and body elements are delivered too.

package main

import (
	"encoding/xml"
	"fmt"
	"strings"

	"github.com/pgaskin/htmlstream"
	"github.com/pgaskin/htmlstream/sax"
)

func main() {
	var page struct {
		Title string `xml:"head>title"`
		Links []struct {
			Href string `xml:"href,attr"`
			Text string `xml:",chardata"`
		} `xml:"body>ul>li>a"`
	}
	r := htmlstream.NewReader(strings.NewReader(`<!DOCTYPE html>
<title>Links &amp; more</title>
<ul>
  <li><a href=/one>One</a>
  <li><a href=/two>Two</a>
</ul>`))
	d := xml.NewTokenDecoder(sax.NewTokenReader(sax.NewReader(r)))
	if err := d.Decode(&page); err != nil {
		fmt.Println(err)
	}
	fmt.Printf("%+v\n", page)

}
Output:
{Title:Links & more Links:[{Href:/one Text:One} {Href:/two Text:Two}]}

func NewTokenReader

func NewTokenReader(r *Reader) *TokenReader

NewTokenReader returns a TokenReader reading the events of r.

func (*TokenReader) Token

func (tr *TokenReader) Token() (xml.Token, error)

Token returns the next token, or io.EOF at the end of the input. The token data is valid until the next call to Token. After an error (including io.EOF), it returns the error again: the *htmlstream.SyntaxError of a SyntaxError event, ErrUntracked, or an error of the Reader.

Jump to

Keyboard shortcuts

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