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 ¶
- func ClarkName(uri, local string) string
- func CompileFunc(impl func(args []interface{}) interface{}) func(f *Function, args []Expr) Expr
- func Literals(exprs ...Expr) bool
- func Node2Number(n dom.Node) float64
- func Node2String(n dom.Node) string
- func Parent(n dom.Node) dom.Node
- func String2Number(s string) float64
- func Value2Boolean(v interface{}) bool
- func Value2Number(v interface{}) float64
- func Value2String(v interface{}) string
- type Arg
- type ArgCountError
- type Args
- type Compiler
- type Context
- type ContextExpr
- type ConversionError
- type DataType
- type Expr
- type Function
- type FunctionMap
- type Functions
- type InvalidValueError
- type Iterator
- func AncestorAxis(n dom.Node) Iterator
- func AncestorOrSelfAxis(n dom.Node) Iterator
- func AttributeAxis(n dom.Node) Iterator
- func ChildAxis(n dom.Node) Iterator
- func DescendantAxis(n dom.Node) Iterator
- func DescendantOrSelfAxis(n dom.Node) Iterator
- func FollowingAxis(n dom.Node) Iterator
- func FollowingSiblingAxis(n dom.Node) Iterator
- func NamespaceAxis(n dom.Node) Iterator
- func ParentAxis(n dom.Node) Iterator
- func PrecedingAxis(n dom.Node) Iterator
- func PrecedingSiblingAxis(n dom.Node) Iterator
- func SelfAxis(n dom.Node) Iterator
- type SignatureError
- type UnresolvedFunctionError
- type UnresolvedPrefixError
- type UnresolvedVariableError
- type VarMustBeNodeSet
- type VariableMap
- type Variables
- type XPath
- func (x *XPath) Eval(n dom.Node, vars Variables) (r interface{}, err error)
- func (x *XPath) EvalBoolean(n dom.Node, vars Variables) (bool, error)
- func (x *XPath) EvalNodeSet(n dom.Node, vars Variables) ([]dom.Node, error)
- func (x *XPath) EvalNumber(n dom.Node, vars Variables) (float64, error)
- func (x *XPath) EvalString(n dom.Node, vars Variables) (string, error)
- func (x *XPath) IsStatic() bool
- func (x *XPath) Returns() DataType
- func (x *XPath) String() string
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CompileFunc ¶
CompileFunc returns a function which compiles given impl to an xpath expression
func Literals ¶
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 ¶
Node2Number returns the string value of the node converted to float64.
func Node2String ¶
Node2String returns string value of the node.
func Parent ¶
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 ¶
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.
func Value2Number ¶
func Value2Number(v interface{}) float64
Value2Number converts given value to a float64. The value must be []dom.Node, string, float64 or boolean.
func Value2String ¶
func Value2String(v interface{}) string
Value2String converts given value to a string. The value must be []dom.Node, string, float64 or boolean.
Types ¶
type Arg ¶
type Arg int
Arg defines the signature of a function argument. It encapsulates: - dataType of argument - cardinality of argument
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 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.
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.
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.
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 ¶
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 FunctionMap ¶
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 ¶
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 ¶
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 ¶
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 ¶
ChildAxis returns Iterator which contains the children of the context node.
This is forward axis.
func DescendantAxis ¶
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 ¶
DescendantOrSelfAxis returns Iterator which contains the context node and the descendants of the context node.
This is forward axis.
func FollowingAxis ¶
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 ¶
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 ¶
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 ¶
ParentAxis returns Iterator which contains the parent of the context node, if there is one.
This is forward axis.
func PrecedingAxis ¶
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 ¶
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.
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 ¶
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 ¶
EvalBoolean evaluates the compiled XPath expression in given context and returns bool value.
The vars argument can be nil.
func (*XPath) EvalNodeSet ¶
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 ¶
EvalNumber evaluates the compiled XPath expression in given context and returns float64 value.
The vars argument can be nil.
func (*XPath) EvalString ¶
EvalString evaluates the compiled XPath expression in given context and returns string value.
The vars argument can be nil.
func (*XPath) IsStatic ¶
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.