Documentation
¶
Overview ¶
Package nokogiri is a pure-Go (no cgo) reimplementation of the core of Ruby's Nokogiri HTML/XML toolkit. Nokogiri is normally a C extension over libxml2 and libxslt; this library instead builds on the pure-Go golang.org/x/net/html tag-soup parser (for Nokogiri::HTML) and encoding/xml (for Nokogiri::XML), exposes a single Node tree over both, and layers an XPath 1.0 engine plus a CSS-selector-to-XPath compiler on top so that at_css/css/at_xpath/xpath behave as Ruby programs expect — all with CGO_ENABLED=0.
Index ¶
- type Attr
- type Builder
- func (b *Builder) Attr(name, value string) *Builder
- func (b *Builder) CDATA(s string) *Builder
- func (b *Builder) Comment(s string) *Builder
- func (b *Builder) Document() *Document
- func (b *Builder) Element(name string, fn func(*Builder)) *Builder
- func (b *Builder) ElementText(name, text string) *Builder
- func (b *Builder) Root() *Node
- func (b *Builder) Text(s string) *Builder
- func (b *Builder) ToHTML() string
- func (b *Builder) ToXML() string
- type Document
- func (d *Document) AtCSS(selector string) (*Node, error)
- func (d *Document) AtXPath(expr string) (*Node, error)
- func (d *Document) CSS(selector string) (*NodeSet, error)
- func (d *Document) NewCDATA(s string) *Node
- func (d *Document) NewComment(s string) *Node
- func (d *Document) NewElement(name string) *Node
- func (d *Document) NewPI(name, data string) *Node
- func (d *Document) NewText(s string) *Node
- func (d *Document) XPath(expr string) (*NodeSet, error)
- type Namespace
- type Node
- func (n *Node) AddChild(child *Node) *Node
- func (n *Node) AddNamespace(prefix, uri string) *Namespace
- func (n *Node) AddNextSibling(sib *Node) *Node
- func (n *Node) AddPreviousSibling(sib *Node) *Node
- func (n *Node) AtCSS(selector string, nsMap map[string]string) (*Node, error)
- func (n *Node) AtXPath(expr string, nsMap map[string]string) (*Node, error)
- func (n *Node) Attribute(name string) string
- func (n *Node) Attributes() map[string]*Attr
- func (n *Node) CSS(selector string, nsMap map[string]string) (*NodeSet, error)
- func (n *Node) Children() *NodeSet
- func (n *Node) Content() string
- func (n *Node) Document() *Document
- func (n *Node) ElementChildren() *NodeSet
- func (n *Node) EvalXPath(expr string, nsMap map[string]string) (any, error)
- func (n *Node) EvalXPathCtx(expr string, nsMap map[string]string, ctx *XPathContext) (any, error)
- func (n *Node) FirstChild() *Node
- func (n *Node) Get(name string) (string, bool)
- func (n *Node) HasAttribute(name string) bool
- func (n *Node) InnerHTML() string
- func (n *Node) InnerXML() string
- func (n *Node) IsCDATA() bool
- func (n *Node) IsComment() bool
- func (n *Node) IsElement() bool
- func (n *Node) IsText() bool
- func (n *Node) LastChild() *Node
- func (n *Node) Namespace() *Namespace
- func (n *Node) NamespaceDeclarations() []*Namespace
- func (n *Node) Namespaces() map[string]string
- func (n *Node) Next() *Node
- func (n *Node) NextElement() *Node
- func (n *Node) NodeName() string
- func (n *Node) NodeType() NodeType
- func (n *Node) Parent() *Node
- func (n *Node) Prepend(child *Node) *Node
- func (n *Node) Previous() *Node
- func (n *Node) PreviousElement() *Node
- func (n *Node) Remove()
- func (n *Node) RemoveAttribute(name string)
- func (n *Node) Replace(repl *Node) *Node
- func (n *Node) Root() *Node
- func (n *Node) SetAttribute(name, value string)
- func (n *Node) SetContent(s string)
- func (n *Node) Text() string
- func (n *Node) ToHTML() string
- func (n *Node) ToS() string
- func (n *Node) ToXML() string
- func (n *Node) Wrap(markup string) (*Node, error)
- func (n *Node) XPath(expr string, nsMap map[string]string) (*NodeSet, error)
- type NodeSet
- func (s *NodeSet) At(i int) *Node
- func (s *NodeSet) CSS(selector string) (*NodeSet, error)
- func (s *NodeSet) Each(fn func(*Node))
- func (s *NodeSet) Empty() bool
- func (s *NodeSet) First() *Node
- func (s *NodeSet) Last() *Node
- func (s *NodeSet) Length() int
- func (s *NodeSet) Nodes() []*Node
- func (s *NodeSet) Text() string
- func (s *NodeSet) XPath(expr string) (*NodeSet, error)
- type NodeType
- type SAXDocument
- func (SAXDocument) CdataBlock(string)
- func (SAXDocument) Characters(string)
- func (SAXDocument) Comment(string)
- func (SAXDocument) EndDocument()
- func (SAXDocument) EndElement(string)
- func (SAXDocument) Error(string)
- func (SAXDocument) ProcessingInstruction(string, string)
- func (SAXDocument) StartDocument()
- func (SAXDocument) StartElement(string, []*Attr)
- type SAXHandler
- type SAXParser
- type XPathContext
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Attr ¶
Attr is a single attribute on an element. Namespace holds the resolved namespace URI when the attribute is namespaced (empty otherwise); Prefix holds the literal prefix as written (e.g. "xml" for xml:lang).
type Builder ¶
type Builder struct {
// contains filtered or unexported fields
}
Builder programmatically constructs an XML (or HTML) document tree, the Go analogue of Nokogiri::XML::Builder. Where Ruby leans on method_missing and blocks, this exposes an explicit, chainable API: Element opens a child element, runs the supplied closure to populate it, and closes it; Text/Comment/CDATA add leaf nodes; Attr sets an attribute on the current element.
func NewHTMLBuilder ¶
func NewHTMLBuilder() *Builder
NewHTMLBuilder starts a new HTML document builder (HTML serialization rules).
func (*Builder) Element ¶
Element opens a child element named name under the current node, invokes fn (if non-nil) with the builder positioned inside it, then restores the previous current node. Returns the builder for chaining.
func (*Builder) ElementText ¶
ElementText is the common leaf case: an element whose only content is text.
type Document ¶
type Document struct {
Node
// contains filtered or unexported fields
}
Document is the root of a parsed tree. It embeds a Node (the DocumentNode) and records whether it came from the HTML or the XML parser, which controls default serialization (HTML void elements, etc.).
func HTML ¶
HTML parses a real-world HTML document with the lenient, HTML5 tree-building algorithm (via the pure-Go golang.org/x/net/html parser), matching Nokogiri::HTML / Nokogiri::HTML5. Malformed "tag soup" is recovered exactly as a browser would: missing end tags are inferred, misnested tags are corrected, and implied <html>/<head>/<body> wrappers are added.
func HTML5 ¶
HTML5 parses an HTML document with the WHATWG HTML5 algorithm, matching Nokogiri::HTML5. Because golang.org/x/net/html already implements the HTML5 tree-building specification, this is the same code path as HTML; the alias exists so ported Ruby that calls Nokogiri::HTML5(...) reads naturally.
func HTMLFragment ¶
HTMLFragment parses a fragment of HTML with no implied document wrappers, matching Nokogiri::HTML::DocumentFragment.parse. The returned Document's children are the fragment's top-level nodes.
func HTMLFragmentReader ¶
HTMLFragmentReader is HTMLFragment reading from an io.Reader.
func HTMLReader ¶
HTMLReader is HTML reading from an io.Reader (Nokogiri accepts an IO too).
func NewDocument ¶
func NewDocument() *Document
NewDocument creates an empty XML Document to hold a freshly built tree, such as an XSLT result tree. Its root is a DocumentNode; append the result with AddChild.
func XML ¶
XML parses a well-formed XML document into the shared Node tree, matching Nokogiri::XML. Namespaces are resolved: an element or attribute in a namespace carries its resolved URI, and the literal prefix as written is preserved for round-tripping. Unlike Nokogiri::HTML this path is strict; a malformed document returns an error.
func (*Document) CSS ¶
CSS runs a CSS query against the document root (Nokogiri::XML::Document#css).
func (*Document) NewCDATA ¶
NewCDATA creates a detached CDATA node (Nokogiri::XML::Document#create_cdata).
func (*Document) NewComment ¶
NewComment creates a detached comment node (Nokogiri::XML::Document#create_comment).
func (*Document) NewElement ¶
NewElement creates a detached element node named name owned by the document, mirroring Nokogiri::XML::Document#create_element.
func (*Document) NewPI ¶
NewPI creates a detached processing-instruction node with target name and the given data (Nokogiri::XML::ProcessingInstruction.new). XSLT builds these for xsl:processing-instruction.
type Node ¶
type Node struct {
Type NodeType
// name is the element/PI/attribute name (local part kept in Name, prefix in
// Prefix). For text/comment/cdata nodes it is the libxml2 pseudo-name
// ("text", "comment", "#cdata-section").
Name string
Prefix string // namespace prefix as written, e.g. "svg" in <svg:rect>
NsURI string // resolved namespace URI for this element, if any
Attrs []*Attr
// contains filtered or unexported fields
}
Node is the shared DOM node produced by BOTH the HTML and the XML parsers and consumed by the XPath and CSS engines. It is a mutable, doubly-linked tree: a node knows its parent, first/last child, and previous/next sibling. The public method set mirrors the slice of Nokogiri::XML::Node that this library targets.
func (*Node) AddChild ¶
AddChild appends child as the last child of n (Nokogiri::XML::Node#add_child / #<<). If child already has a parent it is detached first. Returns child.
func (*Node) AddNamespace ¶
AddNamespace declares an xmlns mapping on n (an empty prefix sets the default namespace) and returns it, mirroring Nokogiri::XML::Node#add_namespace_definition. If the same prefix is already declared on n its URI is updated in place. The declaration takes effect for the node's own resolution and for its descendants.
func (*Node) AddNextSibling ¶
AddNextSibling inserts sib immediately after n (Nokogiri#add_next_sibling).
func (*Node) AddPreviousSibling ¶
AddPreviousSibling inserts sib immediately before n (Nokogiri#add_previous_sibling).
func (*Node) AtCSS ¶
AtCSS returns the first node matching the CSS selector, or nil (Nokogiri#at_css).
func (*Node) AtXPath ¶
AtXPath returns the first node matching the XPath expression, or nil (Nokogiri#at_xpath).
func (*Node) Attribute ¶
Attribute returns the value of the named attribute, or "" if absent. This is the ergonomic form of Nokogiri#[]/#attr.
func (*Node) Attributes ¶
Attributes returns the node's attributes keyed by their qualified name, matching Nokogiri::XML::Node#attributes (best effort; last write wins on a duplicate qualified name).
func (*Node) CSS ¶
CSS evaluates one or more comma-separated CSS selectors against n and returns the matching nodes (Nokogiri::XML::Node#css). Selectors are translated to XPath and evaluated over the descendant axis rooted at n.
func (*Node) ElementChildren ¶
ElementChildren returns only the element children (Nokogiri#element_children).
func (*Node) EvalXPath ¶
EvalXPath evaluates expr and returns the raw XPath object (a *NodeSet, string, float64, or bool), matching how Nokogiri returns scalar results for functions like count()/string(). Node-sets are wrapped as *NodeSet.
func (*Node) EvalXPathCtx ¶
EvalXPathCtx evaluates expr against n with the variable bindings and extension-function resolver carried by ctx (which may be nil). Node-sets are returned as *NodeSet; scalar results as string, float64 or bool — the same object model as EvalXPath.
func (*Node) FirstChild ¶
FirstChild returns the first child node, or nil.
func (*Node) Get ¶
Get returns the value of the named attribute and whether it was present. The lookup matches on the qualified name as written (prefix:local) first, then on the bare local name, mirroring Nokogiri::XML::Node#[].
func (*Node) HasAttribute ¶
HasAttribute reports whether the named attribute is present.
func (*Node) InnerHTML ¶
InnerHTML serializes the node's children with HTML rules (Nokogiri#inner_html). Children of a raw-text element (script/style/…) are emitted verbatim, matching WHATWG serialization.
func (*Node) InnerXML ¶
InnerXML serializes the node's children with XML rules (no pretty-printing).
func (*Node) Namespace ¶
Namespace returns the namespace this node itself belongs to (its resolved prefix and URI), or nil when the node is not in any namespace — mirroring Nokogiri::XML::Node#namespace.
func (*Node) NamespaceDeclarations ¶
NamespaceDeclarations returns the xmlns declarations introduced on this node.
func (*Node) Namespaces ¶
Namespaces returns every xmlns declaration in scope at n — the node's own declarations plus those inherited from its ancestors, nearest first — keyed the way Nokogiri::XML::Node#namespaces keys them: "xmlns" for the default namespace and "xmlns:<prefix>" for a prefixed one. When a prefix is redeclared on a nearer ancestor, the nearer declaration wins (and appears in its position). The implicit "xml" namespace is not included, matching Nokogiri.
func (*Node) NextElement ¶
NextElement returns the next sibling that is an element (Nokogiri#next_element).
func (*Node) NodeName ¶
NodeName returns the libxml2/Nokogiri node name: the qualified tag name for elements, or a pseudo-name for the other node types.
func (*Node) PreviousElement ¶
PreviousElement returns the previous element sibling.
func (*Node) Remove ¶
func (n *Node) Remove()
Remove detaches n from its tree (Nokogiri::XML::Node#remove / #unlink).
func (*Node) RemoveAttribute ¶
RemoveAttribute deletes the named attribute if present (Nokogiri#remove_attribute).
func (*Node) Root ¶
Root returns the document's root element (the first element child of the document node), reached from any node.
func (*Node) SetAttribute ¶
SetAttribute sets (or creates) the named attribute, matching Nokogiri::XML::Node#set_attribute / #[]=.
func (*Node) SetContent ¶
SetContent replaces all children of n with a single text node holding s (Nokogiri::XML::Node#content=).
func (*Node) Text ¶
Text returns the concatenated character data of the node and all descendants, matching Nokogiri#text / #content / #inner_text.
func (*Node) ToHTML ¶
ToHTML serializes the node using HTML rules (Nokogiri#to_html). HTML output is not pretty-printed (WHATWG serialization adds no whitespace).
func (*Node) ToS ¶
ToS serializes the node using the owning document's default (HTML rules for an HTML document, XML rules otherwise), matching Nokogiri#to_s.
func (*Node) ToXML ¶
ToXML serializes the node using XML rules (Nokogiri#to_xml), reproducing libxml2's indentation. A DocumentNode additionally emits the XML declaration and a trailing newline.
func (*Node) Wrap ¶
Wrap parses markup (a single element, using the owning document's parser) and re-parents n inside it, putting the new wrapper where n used to be — the Go analogue of Nokogiri::XML::Node#wrap. It returns the wrapper element.
type NodeSet ¶
type NodeSet struct {
// contains filtered or unexported fields
}
NodeSet is an ordered collection of nodes, the analogue of Nokogiri::XML::NodeSet returned by #css / #xpath / #children.
func NewNodeSet ¶
NewNodeSet builds a *NodeSet from a slice of nodes. XSLT uses it to hand node-set variable values and extension-function results back to the engine.
func (*NodeSet) At ¶
At returns the node at index i, or nil if out of range. Negative indices count from the end, matching Ruby's NodeSet#[].
type NodeType ¶
type NodeType int
NodeType enumerates the node kinds Nokogiri exposes. The numeric values match libxml2's node type constants that Nokogiri surfaces through Node#type so that ported Ruby code comparing against Nokogiri::XML::Node::ELEMENT_NODE (== 1) and friends keeps working.
const ( // ElementNode is a tag such as <div> or <book>. ElementNode NodeType = 1 // AttributeNode is an attribute; only produced when an attribute is exposed // as a node (e.g. via an XPath attribute axis result). AttributeNode NodeType = 2 // TextNode is character data between tags. TextNode NodeType = 3 // CDATANode is a <![CDATA[ ... ]]> section. CDATANode NodeType = 4 // CommentNode is an <!-- ... --> comment. CommentNode NodeType = 8 // DocumentNode is the root document container. DocumentNode NodeType = 9 // DoctypeNode is a <!DOCTYPE ...> declaration. DoctypeNode NodeType = 10 // ProcessingInstructionNode is a <?target data?> instruction. ProcessingInstructionNode NodeType = 7 )
type SAXDocument ¶
type SAXDocument struct{}
SAXDocument provides no-op implementations of every SAXHandler callback, so a handler need only embed it and override the events it cares about — the Go equivalent of subclassing Nokogiri::XML::SAX::Document.
func (SAXDocument) CdataBlock ¶
func (SAXDocument) CdataBlock(string)
CdataBlock is a no-op default.
func (SAXDocument) Characters ¶
func (SAXDocument) Characters(string)
Characters is a no-op default.
func (SAXDocument) EndElement ¶
func (SAXDocument) EndElement(string)
EndElement is a no-op default.
func (SAXDocument) ProcessingInstruction ¶
func (SAXDocument) ProcessingInstruction(string, string)
ProcessingInstruction is a no-op default.
func (SAXDocument) StartDocument ¶
func (SAXDocument) StartDocument()
StartDocument is a no-op default.
func (SAXDocument) StartElement ¶
func (SAXDocument) StartElement(string, []*Attr)
StartElement is a no-op default.
type SAXHandler ¶
type SAXHandler interface {
// StartDocument fires once before any other event.
StartDocument()
// EndDocument fires once after the last event of a successful parse.
EndDocument()
// StartElement fires at an element's start tag. name is the qualified name
// (prefix:local) as written; attrs lists every attribute in source order,
// including xmlns declarations, matching the non-namespaced start_element.
StartElement(name string, attrs []*Attr)
// EndElement fires at an element's end tag (or the implied end of an
// empty-element tag).
EndElement(name string)
// Characters fires for a run of ordinary character data.
Characters(text string)
// Comment fires for a comment's content.
Comment(text string)
// CdataBlock fires for the content of a CDATA section.
CdataBlock(text string)
// ProcessingInstruction fires for a <?target data?> instruction (the XML
// declaration is not reported).
ProcessingInstruction(target, data string)
// Error fires when the parse cannot continue; the parse then stops.
Error(message string)
}
SAXHandler receives streaming parse events, the Go analogue of a Nokogiri::XML::SAX::Document subclass. Every method is a callback; embed SAXDocument to get no-op defaults and override only what you need.
type SAXParser ¶
type SAXParser struct {
// contains filtered or unexported fields
}
SAXParser drives a SAXHandler over an XML source, mirroring Nokogiri::XML::SAX::Parser. Parsing is event-driven; no DOM is built.
func NewSAXParser ¶
func NewSAXParser(h SAXHandler) *SAXParser
NewSAXParser returns a parser that dispatches events to h.
type XPathContext ¶
type XPathContext struct {
// Vars binds $name references. A value may be a *NodeSet, string, float64 or
// bool; other numeric/int kinds are coerced to float64 by NewXPathValue.
Vars map[string]any
// ResolveFunc, when non-nil, is consulted for any function call the built-in
// XPath library does not implement. It receives the function's already-evaluated
// arguments (each a *NodeSet, string, float64 or bool) and returns the result
// plus ok=true, or ok=false to fall through to the built-in "unknown function"
// error. This is where XSLT plugs key(), format-number(), and friends.
ResolveFunc func(name string, args []any) (result any, ok bool)
// Current overrides the node returned by current(). When nil, current() yields
// the context node the expression is evaluated against (the default behaviour).
Current *Node
// Position and Size seed the context position()/last() of the outermost
// expression. XSLT sets them to the processing position and size of the node
// being handled (e.g. inside xsl:for-each). When Position is 0 the defaults
// (1 and 1) are used, matching a bare EvalXPath.
Position int
Size int
}
XPathContext supplies variable bindings and an extension-function resolver to an XPath evaluation. A nil *XPathContext behaves exactly like Node.EvalXPath.
