xpath

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2017 License: BSD-3-Clause Imports: 11 Imported by: 2

README

xpath

License GoDoc Go Report Card Build Status codecov.io

Package xpath provides XPath 1.0 Processor.

This package implements complete specification https://www.w3.org/TR/xpath/.

see Examples for usage.

Documentation

Overview

Package xpath provides XPath 1.0 Processor.

This package implements complete specification https://www.w3.org/TR/xpath/.

See examples for usage.

Example
package main

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

	"github.com/santhosh-tekuri/dom"
	"github.com/santhosh-tekuri/xpath"
)

func main() {
	str := `
	<developer>
		<name>Santhosh Kumar Tekuri</name>
		<email>santhosh.tekuri@gmail.com</email>
	</developer>
	`
	doc, err := dom.Unmarshal(xml.NewDecoder(strings.NewReader(str)))
	if err != nil {
		fmt.Println(err)
		return
	}

	expr, err := new(xpath.Compiler).Compile("/developer/name")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("xpath %v returns value of type %v\n", expr, expr.Returns())

	result, err := expr.EvalString(doc, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("Result: %s", result)
}
Output:

xpath /developer/name returns value of type node-set
Result: Santhosh Kumar Tekuri

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClarkName

func ClarkName(uri, local string) string

ClarkName returns local if uri is empty, otherwise `{uri}local`.

func CompileFunc

func CompileFunc(impl func(args []interface{}) interface{}) func(f *Function, args []Expr) Expr

CompileFunc returns a function which compiles given impl to an xpath expression

func Literals

func Literals(exprs ...Expr) bool

Literals returns true of all given expressions are literal expression.

A literal expressions is an expression which wraps string, float64 or bool. An expression that includes only literals are candidates for simplification.

func Node2Number

func Node2Number(n dom.Node) float64

Node2Number returns the string value of the node converted to float64.

func Node2String

func Node2String(n dom.Node) string

Node2String returns string value of the node.

See https://www.w3.org/TR/xpath/#dt-string-value.

func Parent

func Parent(n dom.Node) dom.Node

Parent returns parent of given dom.Node as per xpath specification.

""" unlike dom specification: - the element is the parent of each of these attribute nodes. - The element is the parent of each of these namespace nodes. """

func String2Number

func String2Number(s string) float64

String2Number converts the string value to float64

func Value2Boolean

func Value2Boolean(v interface{}) bool

Value2Boolean converts given value to a bool. The value must be []dom.Node, string, float64 or boolean.

See https://www.w3.org/TR/xpath/#function-boolean.

func Value2Number

func Value2Number(v interface{}) float64

Value2Number converts given value to a float64. The value must be []dom.Node, string, float64 or boolean.

See https://www.w3.org/TR/xpath/#function-number.

func Value2String

func Value2String(v interface{}) string

Value2String converts given value to a string. The value must be []dom.Node, string, float64 or boolean.

See https://www.w3.org/TR/xpath/#function-string.

Types

type Arg

type Arg int

Arg defines the signature of a function argument. It encapsulates: - dataType of argument - cardinality of argument

func Mandatory

func Mandatory(t DataType) Arg

Mandatory creates function argument which is mandatory of given type.

func Optional

func Optional(t DataType) Arg

Optional creates function argument which is optional of given type.

func Variadic

func Variadic(t DataType) Arg

Variadic creates function argument which is variadic of given type.

type ArgCountError

type ArgCountError string

ArgCountError is the error type returned by *Compiler.Compile function.

It tells that function registered for that clarkName does not accept the number of args specified in xpath expression.

func (ArgCountError) Error

func (e ArgCountError) Error() string

type Args

type Args []Arg

Args represents the signature of function arguments.

func (Args) Valid

func (a Args) Valid() bool

Valid tells whether the signature is valid

type Compiler

type Compiler struct {
	// Namespaces gives bindings of prefix to uri
	Namespaces map[string]string

	// Functions gives access to set of user defined functions.
	Functions Functions
}

A Compiler represents a xpath 1.0 expression compiler.

func (*Compiler) Compile

func (c *Compiler) Compile(str string) (x *XPath, err error)

Compile compiles given xpath 1.0 expression, if successful return a XPath object.

Namespace prefixes and functions are resolved during compilation.

type Context

type Context struct {
	// Node is the current node in context-set
	Node dom.Node

	// Pos is the position of current node in context-set
	Pos int

	// Size is the size of the context-set
	Size int

	// Vars is the set of variable bindings
	Vars Variables
}

Context represents the evaluation context of xpath engine.

func (*Context) Document

func (ctx *Context) Document() *dom.Document

Document returns the Document of current node in context-set

type ContextExpr

type ContextExpr struct{}

ContextExpr represents current node in context.

func (ContextExpr) Eval

func (ContextExpr) Eval(ctx *Context) interface{}

Eval returns []dom.Node of length 1 which contains the current node in context-set

func (ContextExpr) Returns

func (ContextExpr) Returns() DataType

Returns returns the DataType of the value that this expression evaluates to.

type ConversionError

type ConversionError struct {
	// Src is DataType of source value
	Src DataType

	// Target is DataType the source value is requested to convert
	Target DataType
}

ConversionError is the error type returned by *XPath.EvalNodeSet

It tells that the value of type Src cannot be converted to value of type Target

func (ConversionError) Error

func (e ConversionError) Error() string

type DataType

type DataType int

A DataType specifies the type of the value a xpath expression evaluates to.

const (
	// Any means the actual type cannot be statically determined.
	Any DataType = iota

	// NodeSet represents type []dom.Node.
	NodeSet

	// String represents type string.
	String

	// Number represents type float64.
	Number

	// Boolean represents type bool.
	Boolean
)

func TypeOf

func TypeOf(v interface{}) DataType

TypeOf returns xpath type of given value.

func (DataType) String

func (r DataType) String() string

type Expr

type Expr interface {
	// Returns returns the DataType of the value that this expression evaluates to.
	Returns() DataType

	// Eval evaluates against the given context and returns the value
	// In case of any error, it will panic
	Eval(ctx *Context) interface{}
}

Expr is interface used to represent a specific type of xpath expression.

func Simplify

func Simplify(e Expr) Expr

Simplify returns the simplified expression.

Simplification does evaluate all static expressions. An Expr that supports simplification implements: interface{ Simplify() Expr

func Value2Expr

func Value2Expr(v interface{}) Expr

Value2Expr returns literal Expr for given value. The value must be string, float64 or bool.

type Function

type Function struct {
	Returns DataType
	Args    Args
	Compile func(f *Function, args []Expr) Expr
}

Function encapsulates all information required to compile an xpath function call

type FunctionMap

type FunctionMap map[string]*Function

FunctionMap implements Functions interface using map.

Key must be clark-name of function.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/santhosh-tekuri/xpath"
)

func main() {
	join := func(args []interface{}) interface{} {
		sep := args[0].(string)
		var a []string
		for _, v := range args[1:] {
			a = append(a, v.(string))
		}
		return strings.Join(a, sep)
	}

	uri := "www.jroller.com/santhosh/"

	compiler := &xpath.Compiler{
		Namespaces: map[string]string{
			"x": uri,
		},
		Functions: xpath.FunctionMap{
			"{www.jroller.com/santhosh/}join": &xpath.Function{
				Returns: xpath.String,
				Args: xpath.Args{
					xpath.Mandatory(xpath.String),
					xpath.Variadic(xpath.String),
				},
				Compile: xpath.CompileFunc(join),
			},
		},
	}
	expr, err := compiler.Compile("x:join(':', 'one', 'two', 'three')")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("xpath %v returns value of type %v\n", expr, expr.Returns())

	result, err := expr.EvalString(nil, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("Result: %s", result)
}
Output:

xpath x:join(':', 'one', 'two', 'three') returns value of type string
Result: one:two:three

func (FunctionMap) Resolve

func (fm FunctionMap) Resolve(function string) *Function

Resolve returns the *Function bound to given function name. It returns nil if no function is bound.

type Functions

type Functions interface {
	// Resolve find a function bound to the given name in the set of available functions.
	// If there is no such function, it should return nil.
	// The argument is the clark-name of the function
	Resolve(function string) *Function
}

Functions is interface that provides access to the set of user defined functions during xpath expression compilation.

This cannot be used to override XPath built-in functions. In the course of evaluating any single XPath expression, a function must not change.

type InvalidValueError

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

InvalidValueError is the error type returned by *XPath.Eval function.

It tells that function registered returned value other than []dom.Node, string, float64 or boolean

func (InvalidValueError) Error

func (e InvalidValueError) Error() string

type Iterator

type Iterator interface {
	// Next returns the next element in the iteration.
	// Returns nil if the iteration has no more nodes.
	Next() dom.Node
}

Iterator over collection of dom nodes.

func AncestorAxis

func AncestorAxis(n dom.Node) Iterator

AncestorAxis returns Iterator which contains the ancestors of the context node. The ancestors of the context node consist of the parent of context node and the parent's parent and so on; thus, the ancestor axis will always include the root node, unless the context node is the root node.

This is reverse axis.

func AncestorOrSelfAxis

func AncestorOrSelfAxis(n dom.Node) Iterator

AncestorOrSelfAxis returns Iterator which contains the context node and the ancestors of the context node. Thus, the ancestor axis will always include the root node.

This is reverse axis.

func AttributeAxis

func AttributeAxis(n dom.Node) Iterator

AttributeAxis returns Iterator which contains the attributes of the context node. The axis will be empty unless the context node is an element.

This is forward axis.

func ChildAxis

func ChildAxis(n dom.Node) Iterator

ChildAxis returns Iterator which contains the children of the context node.

This is forward axis.

func DescendantAxis

func DescendantAxis(n dom.Node) Iterator

DescendantAxis returns Iterator which contains the descendants of the context node. A descendant is a child or a child of a child and so on. Thus the descendant axis never contains attribute or namespace nodes.

This is forward axis.

func DescendantOrSelfAxis

func DescendantOrSelfAxis(n dom.Node) Iterator

DescendantOrSelfAxis returns Iterator which contains the context node and the descendants of the context node.

This is forward axis.

func FollowingAxis

func FollowingAxis(n dom.Node) Iterator

FollowingAxis returns Iterator which contains all nodes in the same document as the context node that are after the context node in document order, excluding any descendants and excluding attribute nodes and namespace nodes.

This is forward axis.

func FollowingSiblingAxis

func FollowingSiblingAxis(n dom.Node) Iterator

FollowingSiblingAxis returns Iterator which contains all the following siblings of the context node. If the context node is an attribute node or namespace node, the following-sibling axis is empty.

This is forward axis.

func NamespaceAxis

func NamespaceAxis(n dom.Node) Iterator

NamespaceAxis returns Iterator which contains the namespace nodes of the context node. The axis will be empty unless the context node is an element.

This is forward axis.

func ParentAxis

func ParentAxis(n dom.Node) Iterator

ParentAxis returns Iterator which contains the parent of the context node, if there is one.

This is forward axis.

func PrecedingAxis

func PrecedingAxis(n dom.Node) Iterator

PrecedingAxis returns Iterator which contains all nodes in the same document as the context node that are before the context node in document order, excluding any ancestors and excluding attribute nodes and namespace nodes.

This is reverse axis.

func PrecedingSiblingAxis

func PrecedingSiblingAxis(n dom.Node) Iterator

PrecedingSiblingAxis returns Iterator which contains all the preceding siblings of the context node. If the context node is an attribute node or namespace node, the preceding-sibling axis is empty.

This is reverse axis.

func SelfAxis

func SelfAxis(n dom.Node) Iterator

SelfAxis returns Iterator which contains just the context node itself.

This is forward axis.

type SignatureError

type SignatureError string

SignatureError is the error type returned by *Compiler.Compile function.

It tells that function registered for that clarkName has invalid signature. """ the signature is valid only if: - variadic argument can appear only as last argument. - all mandatory arguments must precede optional and variadic arguments. """

func (SignatureError) Error

func (e SignatureError) Error() string

type UnresolvedFunctionError

type UnresolvedFunctionError string

UnresolvedFunctionError is the error type returned by *Compiler.Compile function.

It tells that no function is bound for that clarkName.

func (UnresolvedFunctionError) Error

func (e UnresolvedFunctionError) Error() string

type UnresolvedPrefixError

type UnresolvedPrefixError string

UnresolvedPrefixError is the error type returned by *Compiler.Compile function.

It tells that no URI is bound for that prefix.

func (UnresolvedPrefixError) Error

func (e UnresolvedPrefixError) Error() string

type UnresolvedVariableError

type UnresolvedVariableError string

UnresolvedVariableError is the error type returned by *XPath.Eval function.

It tells that no variable is bound for that clarkName.

func (UnresolvedVariableError) Error

func (e UnresolvedVariableError) Error() string

type VarMustBeNodeSet

type VarMustBeNodeSet string

VarMustBeNodeSet is the error type returned by *XPath.Eval function.

It tells that variable or function that is expected to evaluate to []dom.Node results in value that is not []dom.Node.

func (VarMustBeNodeSet) Error

func (e VarMustBeNodeSet) Error() string

type VariableMap

type VariableMap map[string]interface{}

VariableMap implements Variables interface using map.

Key must be clark-name of variable. Value must be []dom.Node, string, float64 or bool.

Example
package main

import (
	"fmt"

	"github.com/santhosh-tekuri/xpath"
)

func main() {
	uri := "www.jroller.com/santhosh/"

	compiler := &xpath.Compiler{
		Namespaces: map[string]string{
			"ns": uri,
		},
	}
	expr, err := compiler.Compile("$v1 + $v2 * $ns:v3 - $ns:v4")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("xpath %v returns value of type %v\n", expr, expr.Returns())

	result, err := expr.EvalNumber(nil, xpath.VariableMap{
		"v1":                            float64(2),
		"v2":                            float64(3),
		"{www.jroller.com/santhosh/}v3": float64(4),
		xpath.ClarkName(uri, "v4"):      float64(1),
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("Result: %.2f", result)
}
Output:

xpath $v1 + $v2 * $ns:v3 - $ns:v4 returns value of type number
Result: 13.00

func (VariableMap) Eval

func (vm VariableMap) Eval(variable string) interface{}

Eval returns the value bound to given variable. It returns nil if no value is bound.

type Variables

type Variables interface {
	// Eval returns the value of the variable. If there is no such variable,
	// it should return nil. The argument is the clark-name of the variable.
	//
	// The returned value must be nil, []dom.Node, string, float64 or bool.
	Eval(variable string) interface{}
}

Variables is interface that is used to evaluate variable references.

In the course of evaluating any single XPath expression, a variable's value must not change.

type XPath

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

XPath is the representation of a compiled xpath 1.0 expression. A XPath is safe for concurrent use by multiple goroutines.

func (*XPath) Eval

func (x *XPath) Eval(n dom.Node, vars Variables) (r interface{}, err error)

Eval evaluates the compiled XPath expression in the given context and return the result.

The vars argument can be nil. The DataType of returned value will be *XPath.Returns()

func (*XPath) EvalBoolean

func (x *XPath) EvalBoolean(n dom.Node, vars Variables) (bool, error)

EvalBoolean evaluates the compiled XPath expression in given context and returns bool value.

The vars argument can be nil.

func (*XPath) EvalNodeSet

func (x *XPath) EvalNodeSet(n dom.Node, vars Variables) ([]dom.Node, error)

EvalNodeSet evaluates the compiled XPath expression in given context and returns []dom.Node value. if the result cannot be converted to []dom.Node, returns ConversionError

The vars argument can be nil.

func (*XPath) EvalNumber

func (x *XPath) EvalNumber(n dom.Node, vars Variables) (float64, error)

EvalNumber evaluates the compiled XPath expression in given context and returns float64 value.

The vars argument can be nil.

func (*XPath) EvalString

func (x *XPath) EvalString(n dom.Node, vars Variables) (string, error)

EvalString evaluates the compiled XPath expression in given context and returns string value.

The vars argument can be nil.

func (*XPath) IsStatic

func (x *XPath) IsStatic() bool

IsStatic tells whether this xpath is static, i.e, it evaluates to same value every time.

a static expression can be evaluated by passing nil arguments to Eval method.

func (*XPath) Returns

func (x *XPath) Returns() DataType

Returns tells the DataType of value that this expression evaluates to.

func (*XPath) String

func (x *XPath) String() string

String returns the source xpath expression

Jump to

Keyboard shortcuts

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