### Creating an unbounded loading cache Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md Example of creating a loading cache with capacity 0 for unbounded growth, using a custom load function that returns the length of the string key. ```go cache := xpath.NewLoadingCache( func(key interface{}) (interface{}, error) { s := key.(string) return strconv.Itoa(len(s)), nil }, 0, // unbounded ) ``` -------------------------------- ### Compile usage example with Select Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Shows how to compile an expression and select nodes from a NodeNavigator. The error is checked before using the expression; root must be an xpath.NodeNavigator. ```go expr, err := xpath.Compile("//book[price > 30]/title") if err != nil { log.Fatalf("compile failed: %v", err) } iter := expr.Select(root) // root is an xpath.NodeNavigator ``` -------------------------------- ### Expr.String usage example Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Example of using Expr.String to print the original expression string, e.g., "//book[1]". ```go expr := xpath.MustCompile("//book[1]") fmt.Println(expr.String()) // "//book[1]" ``` -------------------------------- ### Replacing RegexpCache with custom capacity Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md Example of replacing the default RegexpCache with a custom loading cache that raises capacity to 1024*1024. Must be done during initialization before any queries run, as replacement is not synchronized with in-flight evaluations. ```go import ( "regexp" "github.com/antchfx/xpath" ) func init() { xpath.RegexpCache = xpath.NewLoadingCache( func(key interface{}) (interface{}, error) { return regexp.Compile(key.(string)) }, 1024*1024, ) } ``` -------------------------------- ### Expr.Select usage example Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Example of using Expr.Select to iterate over matching nodes and print their values. ```go iter := xpath.MustCompile("//book").Select(root) for iter.MoveNext() { fmt.Println(iter.Current().Value()) } ``` -------------------------------- ### Compile error handling examples Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Demonstrates the error messages returned for empty expressions, invalid tokens, and undeclared variables. Each case returns a non-nil error; the messages are illustrative. ```go expr, err := xpath.Compile("") // empty expression if err != nil { fmt.Println(err) // "expr expression is nil" } expr, err = xpath.Compile("//book[") if err != nil { fmt.Println(err) // recovered parse error, e.g. "... has an invalid token" } expr, err = xpath.Compile("$variable") if err != nil { fmt.Println(err) // "undeclared variable in XPath expression: $variable" } ``` -------------------------------- ### Customize RegexpCache with NewLoadingCache Source: https://github.com/antchfx/xpath/blob/master/_autodocs/configuration.md Reassign the exported RegexpCache variable to customize the regexp compilation cache used by matches(), replace(), and friends. The example sets an unbounded cache (capacity 0) with a load function that compiles the key string via regexp.Compile. Reassignment is not synchronized, so perform it before any query runs. ```go xpath.RegexpCache = xpath.NewLoadingCache(func(key interface{}) (interface{}, error) { return regexp.Compile(key.(string)) }, 0) // 0 = unbounded ``` -------------------------------- ### CompileWithNS usage example Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Compiles an expression with a namespace prefix. The compiled axis stores the resolved URI and matches navigators exposing NamespaceURL(). ```go expr, err := xpath.CompileWithNS("//x:book/x:title", map[string]string{ "x": "http://example.com/ns", }) if err != nil { log.Fatalf("compile failed: %v", err) } ``` -------------------------------- ### Select usage example Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Selects nodes from a navigator using a compiled expression. Panics if the expression is invalid. ```go iter := xpath.Select(root, "//book") // panics if the expression is invalid ``` -------------------------------- ### Expr.Evaluate scalar result example Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Example of using Expr.Evaluate to get a scalar result (float64) from an expression like count(//book). The returned value is type-asserted to float64. ```go expr := xpath.MustCompile("count(//book)") val := expr.Evaluate(root) n := val.(float64) ``` -------------------------------- ### Expr.Evaluate node-set result example Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Example of using Expr.Evaluate to handle a node-set result, switching on the dynamic type. For *xpath.NodeIterator, it iterates and prints values; for float64, it prints the number; otherwise prints a generic scalar message. ```go expr := xpath.MustCompile("//book[price > 30]/title") val := expr.Evaluate(root) switch v := val.(type) { case *xpath.NodeIterator: for v.MoveNext() { fmt.Println(v.Current().Value()) } case float64: fmt.Println(v) default: fmt.Printf("scalar result: %v\n", v) } ``` -------------------------------- ### MustCompile usage example Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Compiles an expression without error checking. Evaluate returns a float64 total for sum() expressions. ```go expr := xpath.MustCompile("sum(//price)") val := expr.Evaluate(root) // float64 total ``` -------------------------------- ### Expr.String Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Returns the original expression source string. ```APIDOC ## Expr.String ### Description Returns the original expression source string. ### Method String ### Signature `func (expr *Expr) String() string` ### Parameters None ### Returns - **string** - The expression source ``` -------------------------------- ### Prefix() string Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Returns the namespace prefix associated with the current node, or an empty string when none. ```APIDOC ## Prefix() string ### Description Returns the namespace prefix associated with the current node, or an empty string when none. ### Method Prefix ### Signature ```go Prefix() string ``` ### Returns - **string** - The namespace prefix, or empty string if none. ``` -------------------------------- ### Full NodeNavigator implementation over in-memory DOM Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Canonical pattern for a custom xpath.NodeNavigator. Implements all required methods, including MoveTo() which checks the root node. The main() builds a simple bookstore DOM and selects //book/title, printing "Everyday Italian". Traversal methods returning false signal axis end; the engine never panics on them. ```go package main import ( "bytes" "fmt" "github.com/antchfx/xpath" ) type Node struct { Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node Type int // 0=document, 1=element, 2=text Data string } func (n *Node) Value() string { if n.Type == 2 { // text return n.Data } var buff bytes.Buffer var output func(*Node) output = func(node *Node) { if node.Type == 2 { buff.WriteString(node.Data) } for child := node.FirstChild; child != nil; child = child.NextSibling { output(child) } } output(n) return buff.String() } func (parent *Node) AddChild(n *Node) { n.Parent = parent if parent.FirstChild == nil { parent.FirstChild = n } else { parent.LastChild.NextSibling = n n.PrevSibling = parent.LastChild } parent.LastChild = n } // nav implements xpath.NodeNavigator. type nav struct{ curr, root *Node } func (n *nav) NodeType() xpath.NodeType { switch n.curr.Type { case 2: return xpath.TextNode case 0: return xpath.RootNode } return xpath.ElementNode } func (n *nav) LocalName() string { return n.curr.Data } func (n *nav) Prefix() string { return "" } func (n *nav) Value() string { return n.curr.Value() } func (n *nav) Copy() xpath.NodeNavigator { n2 := *n return &n2 } func (n *nav) MoveToRoot() { n.curr = n.root } func (n *nav) MoveToParent() bool { if node := n.curr.Parent; node != nil { n.curr = node return true } return false } func (n *nav) MoveToNextAttribute() bool { return false } func (n *nav) MoveToChild() bool { if node := n.curr.FirstChild; node != nil { n.curr = node return true } return false } func (n *nav) MoveToFirst() bool { for n.curr.PrevSibling != nil { n.curr = n.curr.PrevSibling } return true } func (n *nav) MoveToNext() bool { if node := n.curr.NextSibling; node != nil { n.curr = node return true t } return false } func (n *nav) MoveToPrevious() bool { if node := n.curr.PrevSibling; node != nil { n.curr = node return true } return false } func (n *nav) MoveTo(other xpath.NodeNavigator) bool { node, ok := other.(*nav) if !ok || node.root != n.root { return false } n.curr = node.curr return true } func main() { // Build: bookstore > book > title "Everyday Italian", price "30.00", ... book := &Node{Type: 1, Data: "book"} title := &Node{Type: 1, Data: "title"} title.AddChild(&Node{Type: 2, Data: "Everyday Italian"}) book.AddChild(title) price := &Node{Type: 1, Data: "price"} price.AddChild(&Node{Type: 2, Data: "30.00"}) book.AddChild(price) store := &Node{Type: 1, Data: "bookstore"} store.AddChild(book) doc := &Node{Type: 0} doc.AddChild(store) var root xpath.NodeNavigator = &nav{curr: doc, root: doc} iter := xpath.MustCompile("//book/title").Select(root) for iter.MoveNext() { fmt.Println(iter.Current().Value()) // "Everyday Italian" } } ``` -------------------------------- ### Expr.Select Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Selects a node set from the given root navigator. Returns an empty iterator for Boolean expressions. ```APIDOC ## Expr.Select ### Description Selects a node set from the given root navigator. Returns an empty iterator for Boolean expressions. ### Method Select ### Signature `func (expr *Expr) Select(root NodeNavigator) *NodeIterator` ### Parameters - **root** (NodeNavigator) - Required - The root navigator to select from ### Returns - **\*NodeIterator** - An iterator over the selected node set ``` -------------------------------- ### query interface definition Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Defines the query interface that every AST node compiles to. It includes methods for selection, evaluation, cloning, value type, and properties. ```go // query.go:30-39 type query interface { Select(iterator) NodeNavigator Evaluate(iterator) interface{} Clone() query ValueType() resultType Properties() queryProp } ``` -------------------------------- ### NodeNavigator interface definition (xpath.go) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Defines the cursor interface the XPath engine uses to traverse a document tree. The library provides no concrete implementation; adapters are supplied by sibling packages like htmlquery, xmlquery, and jsonquery, or can be implemented by the consumer. ```go // xpath.go:32 type NodeNavigator interface { // NodeType returns the XPathNodeType of the current node. NodeType() NodeType // LocalName gets the Name of the current node. LocalName() string // Prefix returns namespace prefix associated with the current node. Prefix() string // Value gets the value of current node. Value() string // Copy does a deep copy of the NodeNavigator and all its components. Copy() NodeNavigator // MoveToRoot moves the NodeNavigator to the root node of the current node. MoveToRoot() // MoveToParent moves the NodeNavigator to the parent node of the current node. MoveToParent() bool // MoveToNextAttribute moves the NodeNavigator to the next attribute on current node. MoveToNextAttribute() bool // MoveToChild moves the NodeNavigator to the first child node of the current node. MoveToChild() bool // MoveToFirst moves the NodeNavigator to the first sibling node of the current node. MoveToFirst() bool // MoveToNext moves the NodeNavigator to the next sibling node of the current node. MoveToNext() bool // MoveToPrevious moves the NodeNavigator to the previous sibling node of the current node. MoveToPrevious() bool // MoveTo moves the NodeNavigator to the same position as the specified NodeNavigator. MoveTo(NodeNavigator) bool } ``` -------------------------------- ### NodeIterator.MoveNext Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Advances the iterator to the next match. Returns false when the iteration is exhausted. ```APIDOC ## NodeIterator.MoveNext ### Description Advances the iterator to the next match. Returns false when the iteration is exhausted. ### Method MoveNext ### Signature `func (t *NodeIterator) MoveNext() bool` ### Parameters None ### Returns - **bool** - True if a next match exists; false when exhausted ``` -------------------------------- ### LocalName() string Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Returns the local (prefix-stripped) name of the current node. ```APIDOC ## LocalName() string ### Description Returns the local (prefix-stripped) name of the current node. ### Method LocalName ### Signature ```go LocalName() string ``` ### Returns - **string** - The local name of the current node. ``` -------------------------------- ### namespaceURL interface check for namespace-uri() Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md The engine dynamically detects a NamespaceURL() method via this interface. When a navigator implements it, namespace-uri() returns the URI from NamespaceURL(); otherwise it falls back to Prefix(). ```go type namespaceURL interface { NamespaceURL() string } if f, ok := v.(namespaceURL); ok { return f.NamespaceURL() } return v.Prefix() ``` -------------------------------- ### NodeNavigator interface definition (xpath.go:32) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Defines the NodeNavigator interface for traversing an XML document or node tree. Implementations must provide navigation and copying methods; MoveTo requires the same tree. Accepted by Compile-family Expr methods and package-level Select, returned by NodeIterator.Current and NodeNavigator.Copy. ```go // xpath.go:32 — full definition in api-reference/node-navigator.md type NodeNavigator interface { NodeType() NodeType LocalName() string Prefix() string Value() string Copy() NodeNavigator MoveToRoot() MoveToParent() bool MoveToNextAttribute() bool MoveToChild() bool MoveToFirst() bool MoveToNext() bool MoveToPrevious() bool MoveTo(NodeNavigator) bool } ``` -------------------------------- ### NodeIterator.Current Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Returns the navigator at the current match position in the iteration. ```APIDOC ## NodeIterator.Current ### Description Returns the navigator at the current match position in the iteration. ### Method Current ### Signature `func (t *NodeIterator) Current() NodeNavigator` ### Parameters None ### Returns - **NodeNavigator** - Navigator at the current match ``` -------------------------------- ### Copy() NodeNavigator Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Returns a deep copy of the navigator, including all internal position state. The engine calls Copy() constantly to snapshot positions, so implementations must return an independent navigator that can be moved without affecting the original. ```APIDOC ## Copy() NodeNavigator ### Description Returns a deep copy of the navigator, including all internal position state. The engine calls Copy() constantly to snapshot positions, so implementations must return an independent navigator that can be moved without affecting the original. ### Method Copy ### Signature ```go Copy() NodeNavigator ``` ### Returns - **NodeNavigator** - A deep copy of the navigator. ``` -------------------------------- ### Expr.Evaluate Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Evaluates the expression against the given root navigator. Returns a boolean, float64, string, or *NodeIterator depending on the expression type. ```APIDOC ## Expr.Evaluate ### Description Evaluates the expression against the given root navigator. Returns a boolean, float64, string, or *NodeIterator depending on the expression type. ### Method Evaluate ### Signature `func (expr *Expr) Evaluate(root NodeNavigator) interface{}` ### Parameters - **root** (NodeNavigator) - Required - The root navigator to evaluate against ### Returns - **interface{}** - The evaluation result: bool, float64, string, or *NodeIterator ``` -------------------------------- ### MoveToFirst() bool Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Moves to the first sibling of the current node. Returns false when there is no preceding sibling to move to (i.e. the node is already first). Called by lastFunc to count the node set backwards from the current position. ```APIDOC ## MoveToFirst() bool ### Description Moves to the first sibling of the current node. Returns false when there is no preceding sibling to move to (i.e. the node is already first). Called by lastFunc to count the node set backwards from the current position. ### Method MoveToFirst ### Signature ```go MoveToFirst() bool ``` ### Returns - **bool** - true if moved to first sibling, false if already first. ``` -------------------------------- ### NewLoadingCache(load loadFunc, capacity int) *loadingCache Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md Creates a new loading cache instance. A loading cache lazily computes values through `load` on first access, memoizes them, and resets the whole map when the configured capacity is reached. ```APIDOC ## NewLoadingCache(load loadFunc, capacity int) *loadingCache ### Description Creates a new loading cache instance. A loading cache lazily computes values through `load` on first access, memoizes them, and — when the configured capacity is reached — resets the whole map. The capacity reset strategy is chosen deliberately over an LRU to keep the library dependency-free. ### Parameters - **load** (loadFunc) - Required - Loader invoked once per unseen key; must return the value and an error. - **capacity** (int) - Required - Maximum number of cached entries. `0` means unbounded growth. Negative values panic. ### Returns `*loadingCache` (unexported concrete type; consumers only use it to assign to `RegexpCache`). ### Panics - `panic("capacity must be >= 0")` when `capacity < 0`. ### Example ```go cache := xpath.NewLoadingCache( func(key interface{}) (interface{}, error) { s := key.(string) return strconv.Itoa(len(s)), nil }, 0, // unbounded ) ``` ### Notes - All access is mutex-protected, so the cache is safe for concurrent evaluation of `matches()`/`replace()`. ``` -------------------------------- ### Capacity reset logic in loading cache Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md When the configured capacity is reached, the whole map is reset instead of using an LRU, keeping the library dependency-free. ```go if c.cap > 0 && len(c.m) >= c.cap { c.m = map[interface{}]interface{}{key: v} c.reset++ } else { c.m[key] = v } ``` -------------------------------- ### MoveToChild() bool Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Moves to the first child node of the current node. Returns false when the current node has no children. ```APIDOC ## MoveToChild() bool ### Description Moves to the first child node of the current node. Returns false when the current node has no children. ### Method MoveToChild ### Signature ```go MoveToChild() bool ``` ### Returns - **bool** - true if moved to first child, false if no children. ``` -------------------------------- ### NewLoadingCache function signature Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md Creates a new loading cache instance. The load function is invoked once per unseen key; capacity 0 means unbounded growth, negative values panic. ```go // cache.go:32 func NewLoadingCache(load loadFunc, capacity int) *loadingCache ``` -------------------------------- ### MoveTo(NodeNavigator) bool Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Moves the navigator to the same position as the specified navigator. Returns false when the other navigator belongs to a different document/tree; a typical implementation type-asserts the argument and compares document roots. ```APIDOC ## MoveTo(NodeNavigator) bool ### Description Moves the navigator to the same position as the specified navigator. Returns false when the other navigator belongs to a different document/tree; a typical implementation type-asserts the argument and compares document roots. ### Method MoveTo ### Signature ```go MoveTo(NodeNavigator) bool ``` ### Parameters - **navigator** (NodeNavigator) - The navigator whose position to move to. ### Returns - **bool** - true if moved successfully, false if the other navigator belongs to a different document/tree. ``` -------------------------------- ### NodeNavigator (interface) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Interface for navigating an XML document or node tree. Implementations are accepted by Compile-family Expr methods and package-level Select. ```APIDOC ## NodeNavigator (interface) ### Description Interface for navigating an XML document or node tree. Implementations are accepted by Compile-family Expr methods and package-level Select. ### Methods - **NodeType** () NodeType - Type of the current node - **LocalName** () string - Local name of the current node - **Prefix** () string - Namespace prefix ("" if none) - **Value** () string - Node value (text content) - **Copy** () NodeNavigator - Deep copy with independent position state - **MoveToRoot** () (void) - Move to document root - **MoveToParent** () bool - Move to parent; false when at root - **MoveToNextAttribute** () bool - Move to next attribute of current element - **MoveToChild** () bool - Move to first child - **MoveToFirst** () bool - Move to first sibling - **MoveToNext** () bool - Move to next sibling - **MoveToPrevious** () bool - Move to previous sibling - **MoveTo** (NodeNavigator) bool - Move to the position of another navigator (same tree required) ### Optional Capability: NamespaceURL() Not part of the interface, but implementations may add `NamespaceURL() string`. The engine detects it dynamically: - `namespace-uri()` returns it - `CompileWithNS` name tests compare it to the resolved namespace URI ``` -------------------------------- ### MoveToNext() bool Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Moves to the next sibling node of the current node. Returns false when the current node is the last sibling. ```APIDOC ## MoveToNext() bool ### Description Moves to the next sibling node of the current node. Returns false when the current node is the last sibling. ### Method MoveToNext ### Signature ```go MoveToNext() bool ``` ### Returns - **bool** - true if moved to next sibling, false if last sibling. ``` -------------------------------- ### RegexpCache variable declaration Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md Process-wide loading cache for string -> *regexp.Regexp mapping, used by matches() and replace(). Exported so clients can customize load func and/or capacity. ```go // cache.go:61-65 var ( // RegexpCache is a loading cache for string -> *regexp.Regexp mapping. It is exported so that in rare cases // client can customize load func and/or capacity. RegexpCache = defaultRegexpCache() ) ``` -------------------------------- ### Catching xpath.Compile errors and recovering from evaluation panics Source: https://github.com/antchfx/xpath/blob/master/_autodocs/errors.md Shows how to handle compile failures from xpath.Compile, which returns plain errors without sentinel types, and how to recover from runtime panics during evaluation with evalSafe. Compile errors cover empty expressions, unclosed strings, invalid tokens, undeclared variables, unsupported functions, arity violations, unknown prefixes, and excessive nesting. Runtime failures like bad regexps or wrong argument types panic and require recovery when evaluating untrusted expressions. ```go expr, err := xpath.Compile(exprString) if err != nil { // All compile failures land here: empty expr, unclosed strings, // invalid tokens, undeclared variables, unsupported functions, // arity violations, unknown prefixes, excessive nesting. return fmt.Errorf("invalid xpath %q: %w", exprString, err) } // Runtime failures (bad regexp at eval time, wrong arg types) panic; // recover around evaluation if untrusted expressions are allowed. func evalSafe(n xpath.NodeNavigator, expr *xpath.Expr) (v interface{}, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("xpath evaluation panicked: %v", r) } }() return expr.Evaluate(n), nil } ``` -------------------------------- ### Current method signature Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-iterator.md Returns the NodeNavigator positioned at the current node. Only meaningful after a successful MoveNext() call. ```go // xpath.go:81 func (t *NodeIterator) Current() NodeNavigator ``` -------------------------------- ### MoveToNextAttribute() bool Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Moves to the next attribute of the current element node. Returns false when the current node is not an element, has no attributes, or all attributes have been visited. Called in a loop by attributeQuery. ```APIDOC ## MoveToNextAttribute() bool ### Description Moves to the next attribute of the current element node. Returns false when the current node is not an element, has no attributes, or all attributes have been visited. Called in a loop by attributeQuery. ### Method MoveToNextAttribute ### Signature ```go MoveToNextAttribute() bool ``` ### Returns - **bool** - true if moved to next attribute, false otherwise. ``` -------------------------------- ### getRegexp function using RegexpCache Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md Internal helper that retrieves a compiled regexp from RegexpCache by pattern, returning an error on failure. ```go func getRegexp(pattern string) (*regexp.Regexp, error) { exp, err := RegexpCache.get(pattern) if err != nil { return nil, err } return exp.(*regexp.Regexp), nil } ``` -------------------------------- ### MoveToRoot() Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Moves the navigator to the root node of the current document, discarding the current position. Used by absoluteQuery. ```APIDOC ## MoveToRoot() ### Description Moves the navigator to the root node of the current document, discarding the current position. Used by absoluteQuery. ### Method MoveToRoot ### Signature ```go MoveToRoot() ``` ``` -------------------------------- ### loadFunc type definition Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Defines the loadFunc type used in the NewLoadingCache signature. It takes a cache key and returns a computed value or an error. ```go // cache.go:9 type loadFunc func(key interface{}) (interface{}, error) ``` -------------------------------- ### CompileWithNS with namespace map Source: https://github.com/antchfx/xpath/blob/master/_autodocs/configuration.md Compile an XPath expression with a namespace map for prefix resolution. The namespaces parameter maps expression prefixes to namespace URIs; a prefix used in the expression but absent from the map fails compilation with 'prefix not defined'. The default Compile passes nil namespaces, so prefixed name tests match by Prefix() string comparison instead. ```go expr, err := xpath.CompileWithNS("//x:book", map[string]string{"x": "http://example.com/ns"}) ``` -------------------------------- ### CompileWithNS function signature (xpath.go:168) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Compiles an expression with a namespace map for QName prefix resolution. Unprefixed expressions are always valid; any prefix used must be in the map or compilation fails with 'prefix not defined'. ```go // xpath.go:168 func CompileWithNS(expr string, namespaces map[string]string) (*Expr, error) ``` -------------------------------- ### Compile / CompileWithNS Source: https://github.com/antchfx/xpath/blob/master/_autodocs/errors.md Compilation functions that return an error on invalid expressions. The returned *Expr is nil on failure. ```APIDOC ## Compile / CompileWithNS ### Description Compiles an XPath expression. Returns an error if the expression is invalid or unsupported. ### Method Function call ### Endpoint `Compile(expr string) (*Expr, error)` `CompileWithNS(expr string, ns map[string]string) (*Expr, error)` ### Parameters - **expr** (string) - Required - The XPath expression to compile. - **ns** (map[string]string) - Required for CompileWithNS - Namespace mappings. ### Errors - `expr expression is nil` - When expr is empty string. - `undeclared variable in XPath expression: ` - When a bare $variable is at the top level. - `undeclared variable in XPath expression: $` - When a $variable is nested anywhere. - `not yet support this function ()` - When an unsupported function is called. ### Response Returns (*Expr, error). On error, *Expr is nil. ``` -------------------------------- ### MoveToParent() bool Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Moves to the parent of the current node. Returns false when there is no parent (the navigator is at the root); on failure the position is unchanged. ```APIDOC ## MoveToParent() bool ### Description Moves to the parent of the current node. Returns false when there is no parent (the navigator is at the root); on failure the position is unchanged. ### Method MoveToParent ### Signature ```go MoveToParent() bool ``` ### Returns - **bool** - true if moved to parent, false if no parent. ``` -------------------------------- ### Value() string Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Returns the value of the current node. For a text node this is its character data; for element nodes it is typically the concatenated text content. The string returned here is what string(), name()-family and comparison operators operate on. ```APIDOC ## Value() string ### Description Returns the value of the current node. For a text node this is its character data; for element nodes it is typically the concatenated text content. The string returned here is what string(), name()-family and comparison operators operate on. ### Method Value ### Signature ```go Value() string ``` ### Returns - **string** - The value of the current node. ``` -------------------------------- ### MoveToPrevious() bool Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Moves to the previous sibling node of the current node. Returns false when the current node is the first sibling. ```APIDOC ## MoveToPrevious() bool ### Description Moves to the previous sibling node of the current node. Returns false when the current node is the first sibling. ### Method MoveToPrevious ### Signature ```go MoveToPrevious() bool ``` ### Returns - **bool** - true if moved to previous sibling, false if first sibling. ``` -------------------------------- ### NodeNavigator Interface Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md The NodeNavigator interface defines the cursor model used by the XPath engine to traverse document trees. It provides methods to inspect the current node and move the cursor through the tree structure. ```APIDOC ## NodeNavigator Interface ### Description The NodeNavigator interface abstracts the underlying document tree (XML, HTML, JSON, or custom) behind a position-based API. It always points at a current node and provides methods to move the cursor and inspect node properties. ### Methods #### NodeType() NodeType - Returns the XPathNodeType of the current node. #### LocalName() string - Gets the Name of the current node. #### Prefix() string - Returns the namespace prefix associated with the current node. #### Value() string - Gets the value of the current node. #### Copy() NodeNavigator - Does a deep copy of the NodeNavigator and all its components. #### MoveToRoot() - Moves the NodeNavigator to the root node of the current node. #### MoveToParent() bool - Moves the NodeNavigator to the parent node of the current node. Returns true if successful. #### MoveToNextAttribute() bool - Moves the NodeNavigator to the next attribute on the current node. Returns true if successful. #### MoveToChild() bool - Moves the NodeNavigator to the first child node of the current node. Returns true if successful. #### MoveToFirst() bool - Moves the NodeNavigator to the first sibling node of the current node. Returns true if successful. #### MoveToNext() bool - Moves the NodeNavigator to the next sibling node of the current node. Returns true if successful. #### MoveToPrevious() bool - Moves the NodeNavigator to the previous sibling node of the current node. Returns true if successful. #### MoveTo(NodeNavigator) bool - Moves the NodeNavigator to the same position as the specified NodeNavigator. Returns true if successful. ### Interface Definition ```go type NodeNavigator interface { NodeType() NodeType LocalName() string Prefix() string Value() string Copy() NodeNavigator MoveToRoot() MoveToParent() bool MoveToNextAttribute() bool MoveToChild() bool MoveToFirst() bool MoveToNext() bool MoveToPrevious() bool MoveTo(NodeNavigator) bool } ``` ``` -------------------------------- ### MoveNext method signature Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-iterator.md Advances the cursor to the next matched node. Returns true when a match is found, false when exhausted. ```go // xpath.go:86 func (t *NodeIterator) MoveNext() bool ``` -------------------------------- ### loadFunc type definition Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md Unexported function type used by NewLoadingCache; must return the value and an error. ```go type loadFunc func(key interface{}) (interface{}, error) ``` -------------------------------- ### NodeType constants definition (xpath.go:9) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Defines the NodeType integer type and its constants for XML node kinds. RootNode through CommentNode are exported; allNode is unexported and used internally for node() and * tests. Produced by NodeNavigator.NodeType() and consumed by node-test predicates. ```go // xpath.go:9 type NodeType int const ( // RootNode is a root node of the XML document or node tree. RootNode NodeType = iota // ElementNode is an element, such as . ElementNode // AttributeNode is an attribute, such as id='123'. AttributeNode // TextNode is the text content of a node. TextNode // CommentNode is a comment node, such as CommentNode // allNode is any types of node, used by xpath package only to predicate match. allNode ) ``` -------------------------------- ### Iterate over selected nodes with Current Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-iterator.md Selects all book nodes and prints their local name and value. Uses MoveNext and Current. ```go iter := xpath.MustCompile("//book").Select(root) for iter.MoveNext() { n := iter.Current() fmt.Printf("%s %s\n", n.LocalName(), n.Value()) } ``` -------------------------------- ### resultType and xpathResultType definitions Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Defines the resultType type and the xpathResultType struct with constants for Boolean, Number, String, NodeSet, and Any. These are used by Expr.Evaluate to map results to Go types. ```go // query.go:12-21 type resultType int var xpathResultType = struct { Boolean resultType Number resultType String resultType NodeSet resultType Any resultType }{ Boolean: 0, Number: 1, String: 2, NodeSet: 3, Any: 4, } ``` -------------------------------- ### NodeType Source: https://github.com/antchfx/xpath/blob/master/_autodocs/types.md Defines the type of a node in the XML document or node tree. Used by NodeNavigator.NodeType() and node-test predicates. ```APIDOC ## NodeType ### Description Defines the type of a node in the XML document or node tree. Used by NodeNavigator.NodeType() and node-test predicates. ### Constants - **RootNode** (NodeType) - Value: 0 - Root of the document/node tree - **ElementNode** (NodeType) - Value: 1 - An element, e.g. `` - **AttributeNode** (NodeType) - Value: 2 - An attribute, e.g. `id='123'` - **TextNode** (NodeType) - Value: 3 - Text content of a node - **CommentNode** (NodeType) - Value: 4 - A comment node, e.g. `` - **allNode** (NodeType) - Value: 5 - **Unexported.** "Any node type", used internally (e.g. for `node()` and `*` tests) ### Usage Produced by `NodeNavigator.NodeType()`; consumed by the node-test predicates of every axis. ``` -------------------------------- ### RegexpCache (variable) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/cache.md Process-wide cache used by matches() and replace() XPath functions. It is exported so clients can customize the load function and/or capacity in rare cases. ```APIDOC ## RegexpCache (variable) ### Description Process-wide cache used by every `matches()` / `replace()` evaluation via `getRegexp(pattern)`. It is exported so that in rare cases client can customize load func and/or capacity. ### Type `*loadingCache` (unexported concrete struct) ### Defaults - **capacity**: `65536` (`defaultCap`) - **load func**: `regexp.Compile` on the key as `string` ### Usage Replace the variable wholesale during initialization before any queries run. ### Example ```go import ( "regexp" "github.com/antchfx/xpath" ) func init() { xpath.RegexpCache = xpath.NewLoadingCache( func(key interface{}) (interface{}, error) { return regexp.Compile(key.(string)) }, 1024*1024, ) } ``` ### Notes - Replacing the cache is not synchronized with in-flight evaluations; do it during initialization. ``` -------------------------------- ### Expr.String method signature Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Method signature for Expr.String, which returns the original expression source string passed to the compiler. ```go // xpath.go:139 func (expr *Expr) String() string ``` -------------------------------- ### Select function signature (xpath.go:102, deprecated) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Deprecated convenience helper that compiles and selects a node set. Panics on malformed expressions because there is no error return; use Compile/Expr.Select() instead. ```go // xpath.go:102 func Select(root NodeNavigator, expr string) *NodeIterator ``` -------------------------------- ### CompileWithNS(expr string, namespaces map[string]string) (*Expr, error) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Compiles an expression, resolving QName prefixes found in the expression through the supplied namespace map. By default the resolver is nil, so unprefixed expressions are always valid; any prefix used in the expression must be present in the map or compilation fails with `prefix not defined`. ```APIDOC ## CompileWithNS(expr string, namespaces map[string]string) (*Expr, error) ### Description Compiles an expression, resolving QName prefixes found in the expression through the supplied namespace map. By default the resolver is nil, so unprefixed expressions are always valid; any prefix used in the expression must be present in the map or compilation fails with `prefix not defined`. ### Method Function ### Signature func CompileWithNS(expr string, namespaces map[string]string) (*Expr, error) ### Parameters - **expr** (string) - Required - The XPath expression source. An empty string is rejected. - **namespaces** (map[string]string) - Required - Maps an expression prefix to a namespace URI, e.g. `{"x": "http://example.com/ns"}`. May be nil for expressions without prefixed names. ### Returns - (*Expr, error) ### Example ```go expr, err := xpath.CompileWithNS("//x:book/x:title", map[string]string{ "x": "http://example.com/ns", }) if err != nil { log.Fatalf("compile failed: %v", err) } ``` ``` -------------------------------- ### Compile function signature (xpath.go:144) Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Compiles an XPath expression string into an *Expr. Returns an error for unparseable expressions; empty strings are rejected. Parse-time panics are recovered and converted to errors inside build(). ```go // xpath.go:144 func Compile(expr string) (*Expr, error) ``` -------------------------------- ### Current() NodeNavigator Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-iterator.md Returns the NodeNavigator positioned at the current node, which is the node most recently produced by MoveNext. This method is only meaningful after a successful MoveNext() call; before the first call, the navigator sits at the context node passed to Select. ```APIDOC ## Current() NodeNavigator ### Description Returns the NodeNavigator positioned at the current node, which is the node most recently produced by MoveNext. This method is only meaningful after a successful MoveNext() call; before the first call, the navigator sits at the context node passed to Select. ### Method Current ### Endpoint NodeIterator.Current() ### Parameters None. ### Returns - **NodeNavigator** - The navigator pointing at the current match. ### Example ```go iter := xpath.MustCompile("//book").Select(root) for iter.MoveNext() { n := iter.Current() fmt.Printf("%s %s\n", n.LocalName(), n.Value()) } ``` ``` ```go iter := xpath.MustCompile("//book").Select(root) for iter.MoveNext() { n := iter.Current() fmt.Printf("%s %s\n", n.LocalName(), n.Value()) } ``` -------------------------------- ### Expr.String Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Returns the original expression source string passed to the compiler. ```APIDOC ## Expr.String ### Description Returns the original expression source string passed to the compiler. ### Method String ### Endpoint func (expr *Expr) String() string ### Parameters None ### Returns - **string** - The original expression source string. ### Request Example ```go expr := xpath.MustCompile("//book[1]") fmt.Println(expr.String()) // "//book[1]" ``` ``` -------------------------------- ### Select(root NodeNavigator, expr string) *NodeIterator Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/expr.md Deprecated convenience helper: compiles expr and selects a node set. Because there is no error return, a compile failure panics. The GoDoc comment recommends using Compile/Expr.Select() instead. ```APIDOC ## Select(root NodeNavigator, expr string) *NodeIterator ### Description Deprecated convenience helper: compiles expr and selects a node set. Because there is no error return, a compile failure panics. The GoDoc comment recommends using Compile/Expr.Select() instead. ### Method Function ### Signature func Select(root NodeNavigator, expr string) *NodeIterator ### Parameters - **root** (NodeNavigator) - Required - Navigator cursor positioned at the context node. - **expr** (string) - Required - XPath expression to compile and run. ### Returns - *NodeIterator - Panics on a malformed expression. ### Example ```go iter := xpath.Select(root, "//book") // panics if the expression is invalid ``` ``` -------------------------------- ### Count nodes with MoveNext Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-iterator.md Counts the number of title nodes by iterating with MoveNext. ```go expr := xpath.MustCompile("//title") iter := expr.Select(navigator) count := 0 for iter.MoveNext() { count++ } fmt.Println(count) ``` -------------------------------- ### MoveNext() bool Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-iterator.md Advances the cursor to the next matched node. Returns true when a match was found (use Current() to read it) and false when the node set is exhausted. If the underlying expression is Boolean-typed, it returns false immediately, as Boolean expressions yield no nodes through the iterator. ```APIDOC ## MoveNext() bool ### Description Advances the cursor to the next matched node. Returns true when a match was found (use Current() to read it) and false when the node set is exhausted. If the underlying expression is Boolean-typed, it returns false immediately, as Boolean expressions yield no nodes through the iterator. ### Method MoveNext ### Endpoint NodeIterator.MoveNext() ### Parameters None. ### Returns - **bool** - true if a next node is available; false when the node set is exhausted or the expression is Boolean-typed. ### Behavior Details - If the compiled expression's ValueType() is Boolean, returns false immediately. - Otherwise calls t.query.Select(t); if the query returns nil, the iteration ends. - On a match, moves the navigator to the matched node via t.node.MoveTo(n), falling back to n.Copy(). ### Example ```go expr := xpath.MustCompile("//title") iter := expr.Select(navigator) count := 0 for iter.MoveNext() { count++ } fmt.Println(count) ``` ### Scalar (Boolean) Expression Example ```go // "boolean(...)" evaluates to a Boolean; Select() marks the iterator scalar iter := xpath.MustCompile("boolean(//book)").Select(root) if iter.MoveNext() { fmt.Println("matched") // never reached } // Use Evaluate() for scalar results instead: val := xpath.MustCompile("boolean(//book)").Evaluate(root) fmt.Println(val.(bool)) ``` ``` ```go expr := xpath.MustCompile("//title") iter := expr.Select(navigator) count := 0 for iter.MoveNext() { count++ } fmt.Println(count) ``` ```go // "boolean(...)" evaluates to a Boolean; Select() marks the iterator scalar iter := xpath.MustCompile("boolean(//book)").Select(root) if iter.MoveNext() { fmt.Println("matched") // never reached } // Use Evaluate() for scalar results instead: val := xpath.MustCompile("boolean(//book)").Evaluate(root) fmt.Println(val.(bool)) ``` -------------------------------- ### NodeType() NodeType Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-navigator.md Returns the NodeType of the current node: one of RootNode, ElementNode, AttributeNode, TextNode, CommentNode. Note that allNode is unexported and used internally. ```APIDOC ## NodeType() NodeType ### Description Returns the NodeType of the current node: one of RootNode, ElementNode, AttributeNode, TextNode, CommentNode. Note that allNode is unexported and used internally. ### Method NodeType ### Signature ```go NodeType() NodeType ``` ### Returns - **NodeType** - The type of the current node. ``` -------------------------------- ### NodeIterator struct definition Source: https://github.com/antchfx/xpath/blob/master/_autodocs/api-reference/node-iterator.md The NodeIterator struct holds the navigator, query, and scalar flag. All fields are unexported. ```go // xpath.go:74 type NodeIterator struct { node NodeNavigator query query scalar bool } ```