feat: Inital commit
This commit is contained in:
+32
@@ -0,0 +1,32 @@
|
||||
# vscode
|
||||
.vscode
|
||||
debug
|
||||
*.test
|
||||
|
||||
./build
|
||||
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
# XPath
|
||||
|
||||
[](https://godoc.org/github.com/antchfx/xpath)
|
||||
[](https://coveralls.io/github/antchfx/xpath?branch=master)
|
||||
[](https://github.com/antchfx/xpath/actions/workflows/testing.yml)
|
||||
[](https://goreportcard.com/report/github.com/antchfx/xpath)
|
||||
|
||||
XPath is Go package provides selecting nodes from XML, HTML or other documents using XPath expression.
|
||||
|
||||
# Implementation
|
||||
|
||||
- [htmlquery](https://github.com/antchfx/htmlquery) - an XPath query package for HTML document
|
||||
|
||||
- [xmlquery](https://github.com/antchfx/xmlquery) - an XPath query package for XML document.
|
||||
|
||||
- [jsonquery](https://github.com/antchfx/jsonquery) - an XPath query package for JSON document
|
||||
|
||||
# Supported Features
|
||||
|
||||
#### The basic XPath patterns.
|
||||
|
||||
> The basic XPath patterns cover 90% of the cases that most stylesheets will need.
|
||||
|
||||
- `node` : Selects all child elements with nodeName of node.
|
||||
|
||||
- `*` : Selects all child elements.
|
||||
|
||||
- `@attr` : Selects the attribute attr.
|
||||
|
||||
- `@*` : Selects all attributes.
|
||||
|
||||
- `node()` : Matches an org.w3c.dom.Node.
|
||||
|
||||
- `text()` : Matches a org.w3c.dom.Text node.
|
||||
|
||||
- `comment()` : Matches a comment.
|
||||
|
||||
- `.` : Selects the current node.
|
||||
|
||||
- `..` : Selects the parent of current node.
|
||||
|
||||
- `/` : Selects the document node.
|
||||
|
||||
- `a[expr]` : Select only those nodes matching a which also satisfy the expression expr.
|
||||
|
||||
- `a[n]` : Selects the nth matching node matching a When a filter's expression is a number, XPath selects based on position.
|
||||
|
||||
- `a/b` : For each node matching a, add the nodes matching b to the result.
|
||||
|
||||
- `a//b` : For each node matching a, add the descendant nodes matching b to the result.
|
||||
|
||||
- `//b` : Returns elements in the entire document matching b.
|
||||
|
||||
- `a|b` : All nodes matching a or b, union operation(not boolean or).
|
||||
|
||||
- `(a, b, c)` : Evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence
|
||||
|
||||
- `(a/b)` : Selects all matches nodes as grouping set.
|
||||
|
||||
#### Node Axes
|
||||
|
||||
- `child::*` : The child axis selects children of the current node.
|
||||
|
||||
- `child::node()`: Selects all the children of the context node.
|
||||
- `child::text()`: Selects all text node children of the context node.
|
||||
|
||||
- `descendant::*` : The descendant axis selects descendants of the current node. It is equivalent to '//'.
|
||||
|
||||
- `descendant-or-self::*` : Selects descendants including the current node.
|
||||
|
||||
- `attribute::*` : Selects attributes of the current element. It is equivalent to @\*
|
||||
|
||||
- `following-sibling::*` : Selects nodes after the current node.
|
||||
|
||||
- `preceding-sibling::*` : Selects nodes before the current node.
|
||||
|
||||
- `following::*` : Selects the first matching node following in document order, excluding descendants.
|
||||
|
||||
- `preceding::*` : Selects the first matching node preceding in document order, excluding ancestors.
|
||||
|
||||
- `parent::*` : Selects the parent if it matches. The '..' pattern from the core is equivalent to 'parent::node()'.
|
||||
|
||||
- `ancestor::*` : Selects matching ancestors.
|
||||
|
||||
- `ancestor-or-self::*` : Selects ancestors including the current node.
|
||||
|
||||
- `self::*` : Selects the current node. '.' is equivalent to 'self::node()'.
|
||||
|
||||
#### Expressions
|
||||
|
||||
The gxpath supported three types: number, boolean, string.
|
||||
|
||||
- `path` : Selects nodes based on the path.
|
||||
|
||||
- `a = b` : Standard comparisons.
|
||||
|
||||
- `a = b` : True if a equals b.
|
||||
- `a != b` : True if a is not equal to b.
|
||||
- `a < b` : True if a is less than b.
|
||||
- `a <= b` : True if a is less than or equal to b.
|
||||
- `a > b` : True if a is greater than b.
|
||||
- `a >= b` : True if a is greater than or equal to b.
|
||||
|
||||
- `a + b` : Arithmetic expressions.
|
||||
|
||||
- `- a` Unary minus
|
||||
- `a + b` : Addition
|
||||
- `a - b` : Subtraction
|
||||
- `a * b` : Multiplication
|
||||
- `a div b` : Division
|
||||
- `a mod b` : Modulus (division remainder)
|
||||
|
||||
- `a or b` : Boolean `or` operation.
|
||||
|
||||
- `a and b` : Boolean `and` operation.
|
||||
|
||||
- `(expr)` : Parenthesized expressions.
|
||||
|
||||
- `fun(arg1, ..., argn)` : Function calls:
|
||||
|
||||
| Function | Supported |
|
||||
| ----------------------- | --------- |
|
||||
| `boolean()` | ✓ |
|
||||
| `ceiling()` | ✓ |
|
||||
| `choose()` | ✗ |
|
||||
| `concat()` | ✓ |
|
||||
| `contains()` | ✓ |
|
||||
| `count()` | ✓ |
|
||||
| `current()` | ✗ |
|
||||
| `document()` | ✗ |
|
||||
| `element-available()` | ✗ |
|
||||
| `ends-with()` | ✓ |
|
||||
| `false()` | ✓ |
|
||||
| `floor()` | ✓ |
|
||||
| `format-number()` | ✗ |
|
||||
| `function-available()` | ✗ |
|
||||
| `generate-id()` | ✗ |
|
||||
| `id()` | ✗ |
|
||||
| `key()` | ✗ |
|
||||
| `lang()` | ✗ |
|
||||
| `last()` | ✓ |
|
||||
| `local-name()` | ✓ |
|
||||
| `lower-case()`[^1] | ✓ |
|
||||
| `matches()` | ✓ |
|
||||
| `name()` | ✓ |
|
||||
| `namespace-uri()` | ✓ |
|
||||
| `normalize-space()` | ✓ |
|
||||
| `not()` | ✓ |
|
||||
| `number()` | ✓ |
|
||||
| `position()` | ✓ |
|
||||
| `replace()` | ✓ |
|
||||
| `reverse()` | ✓ |
|
||||
| `round()` | ✓ |
|
||||
| `starts-with()` | ✓ |
|
||||
| `string()` | ✓ |
|
||||
| `string-join()`[^1] | ✓ |
|
||||
| `string-length()` | ✓ |
|
||||
| `substring()` | ✓ |
|
||||
| `substring-after()` | ✓ |
|
||||
| `substring-before()` | ✓ |
|
||||
| `sum()` | ✓ |
|
||||
| `system-property()` | ✗ |
|
||||
| `translate()` | ✓ |
|
||||
| `true()` | ✓ |
|
||||
| `unparsed-entity-url()` | ✗ |
|
||||
|
||||
[^1]: XPath-2.0 expression
|
||||
+718
@@ -0,0 +1,718 @@
|
||||
package xpath
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type flag int
|
||||
|
||||
var flagsEnum = struct {
|
||||
None flag
|
||||
SmartDesc flag
|
||||
PosFilter flag
|
||||
Filter flag
|
||||
Condition flag
|
||||
}{
|
||||
None: 0,
|
||||
SmartDesc: 1,
|
||||
PosFilter: 2,
|
||||
Filter: 4,
|
||||
Condition: 8,
|
||||
}
|
||||
|
||||
type builderProp int
|
||||
|
||||
var builderProps = struct {
|
||||
None builderProp
|
||||
PosFilter builderProp
|
||||
HasPosition builderProp
|
||||
HasLast builderProp
|
||||
NonFlat builderProp
|
||||
}{
|
||||
None: 0,
|
||||
PosFilter: 1,
|
||||
HasPosition: 2,
|
||||
HasLast: 4,
|
||||
NonFlat: 8,
|
||||
}
|
||||
|
||||
// builder provides building an XPath expressions.
|
||||
type builder struct {
|
||||
parseDepth int
|
||||
firstInput query
|
||||
}
|
||||
|
||||
// axisPredicate creates a predicate to predicating for this axis node.
|
||||
func axisPredicate(root *axisNode) func(NodeNavigator) bool {
|
||||
nametest := root.LocalName != "" || root.Prefix != ""
|
||||
predicate := func(n NodeNavigator) bool {
|
||||
if root.typeTest == n.NodeType() || root.typeTest == allNode {
|
||||
if nametest {
|
||||
type namespaceURL interface {
|
||||
NamespaceURL() string
|
||||
}
|
||||
if ns, ok := n.(namespaceURL); ok && root.hasNamespaceURI {
|
||||
return root.LocalName == n.LocalName() && root.namespaceURI == ns.NamespaceURL()
|
||||
}
|
||||
if root.LocalName == n.LocalName() && root.Prefix == n.Prefix() {
|
||||
return true
|
||||
}
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
return predicate
|
||||
}
|
||||
|
||||
// processAxis processes a query for the XPath axis node.
|
||||
func (b *builder) processAxis(root *axisNode, flags flag, props *builderProp) (query, error) {
|
||||
var (
|
||||
err error
|
||||
qyInput query
|
||||
qyOutput query
|
||||
)
|
||||
b.firstInput = nil
|
||||
predicate := axisPredicate(root)
|
||||
|
||||
if root.Input == nil {
|
||||
qyInput = &contextQuery{}
|
||||
*props = builderProps.None
|
||||
} else {
|
||||
inputFlags := flagsEnum.None
|
||||
if (flags & flagsEnum.Filter) == 0 {
|
||||
if root.AxisType == "child" && (root.Input.Type() == nodeAxis) {
|
||||
if input := root.Input.(*axisNode); input.AxisType == "descendant-or-self" {
|
||||
var qyGrandInput query
|
||||
if input.Input != nil {
|
||||
qyGrandInput, err = b.processNode(input.Input, flagsEnum.SmartDesc, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
qyGrandInput = &contextQuery{}
|
||||
}
|
||||
qyOutput = &descendantQuery{name: root.LocalName, Input: qyGrandInput, Predicate: predicate, Self: false}
|
||||
*props |= builderProps.NonFlat
|
||||
return qyOutput, nil
|
||||
}
|
||||
}
|
||||
if root.AxisType == "descendant" || root.AxisType == "descendant-or-self" {
|
||||
inputFlags |= flagsEnum.SmartDesc
|
||||
}
|
||||
}
|
||||
|
||||
qyInput, err = b.processNode(root.Input, inputFlags, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
switch root.AxisType {
|
||||
case "ancestor":
|
||||
qyOutput = &ancestorQuery{name: root.LocalName, Input: qyInput, Predicate: predicate}
|
||||
*props |= builderProps.NonFlat
|
||||
case "ancestor-or-self":
|
||||
qyOutput = &ancestorQuery{name: root.LocalName, Input: qyInput, Predicate: predicate, Self: true}
|
||||
*props |= builderProps.NonFlat
|
||||
case "attribute":
|
||||
qyOutput = &attributeQuery{name: root.LocalName, Input: qyInput, Predicate: predicate}
|
||||
case "child":
|
||||
if (*props & builderProps.NonFlat) == 0 {
|
||||
qyOutput = &childQuery{name: root.LocalName, Input: qyInput, Predicate: predicate}
|
||||
} else {
|
||||
qyOutput = &cachedChildQuery{name: root.LocalName, Input: qyInput, Predicate: predicate}
|
||||
}
|
||||
case "descendant":
|
||||
if (flags & flagsEnum.SmartDesc) != flagsEnum.None {
|
||||
qyOutput = &descendantOverDescendantQuery{name: root.LocalName, Input: qyInput, MatchSelf: false, Predicate: predicate}
|
||||
} else {
|
||||
qyOutput = &descendantQuery{name: root.LocalName, Input: qyInput, Predicate: predicate}
|
||||
}
|
||||
*props |= builderProps.NonFlat
|
||||
case "descendant-or-self":
|
||||
if (flags & flagsEnum.SmartDesc) != flagsEnum.None {
|
||||
qyOutput = &descendantOverDescendantQuery{name: root.LocalName, Input: qyInput, MatchSelf: true, Predicate: predicate}
|
||||
} else {
|
||||
qyOutput = &descendantQuery{name: root.LocalName, Input: qyInput, Predicate: predicate, Self: true}
|
||||
}
|
||||
*props |= builderProps.NonFlat
|
||||
case "following":
|
||||
qyOutput = &followingQuery{Input: qyInput, Predicate: predicate}
|
||||
*props |= builderProps.NonFlat
|
||||
case "following-sibling":
|
||||
qyOutput = &followingQuery{Input: qyInput, Predicate: predicate, Sibling: true}
|
||||
case "parent":
|
||||
qyOutput = &parentQuery{Input: qyInput, Predicate: predicate}
|
||||
case "preceding":
|
||||
qyOutput = &precedingQuery{Input: qyInput, Predicate: predicate}
|
||||
*props |= builderProps.NonFlat
|
||||
case "preceding-sibling":
|
||||
qyOutput = &precedingQuery{Input: qyInput, Predicate: predicate, Sibling: true}
|
||||
case "self":
|
||||
qyOutput = &selfQuery{Input: qyInput, Predicate: predicate}
|
||||
case "namespace":
|
||||
// haha,what will you do someting??
|
||||
default:
|
||||
err = fmt.Errorf("unknown axe type: %s", root.AxisType)
|
||||
return nil, err
|
||||
}
|
||||
return qyOutput, nil
|
||||
}
|
||||
|
||||
func canBeNumber(q query) bool {
|
||||
if q.ValueType() != xpathResultType.Any {
|
||||
return q.ValueType() == xpathResultType.Number
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// processFilterNode builds query for the XPath filter predicate.
|
||||
func (b *builder) processFilter(root *filterNode, flags flag, props *builderProp) (query, error) {
|
||||
first := (flags & flagsEnum.Filter) == 0
|
||||
|
||||
qyInput, err := b.processNode(root.Input, (flags | flagsEnum.Filter), props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
firstInput := b.firstInput
|
||||
|
||||
var propsCond builderProp
|
||||
cond, err := b.processNode(root.Condition, flags, &propsCond)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Checking whether is number
|
||||
if canBeNumber(cond) || ((propsCond & (builderProps.HasPosition | builderProps.HasLast)) != 0) {
|
||||
propsCond |= builderProps.HasPosition
|
||||
flags |= flagsEnum.PosFilter
|
||||
}
|
||||
|
||||
if root.Input.Type() != nodeFilter {
|
||||
*props &= ^builderProps.PosFilter
|
||||
}
|
||||
|
||||
if (propsCond & builderProps.HasPosition) != 0 {
|
||||
*props |= builderProps.PosFilter
|
||||
}
|
||||
|
||||
if (propsCond & builderProps.HasPosition) != builderProps.None {
|
||||
if (propsCond & builderProps.HasLast) != 0 {
|
||||
// https://github.com/antchfx/xpath/issues/76
|
||||
// https://github.com/antchfx/xpath/issues/78
|
||||
if qyFunc, ok := cond.(*functionQuery); ok {
|
||||
switch qyFunc.Input.(type) {
|
||||
case *filterQuery:
|
||||
cond = &lastFuncQuery{Input: qyFunc.Input}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
merge := (qyInput.Properties() & queryProps.Merge) != 0
|
||||
if first && firstInput != nil {
|
||||
if merge && ((*props & builderProps.PosFilter) != 0) {
|
||||
var (
|
||||
rootQuery = &contextQuery{}
|
||||
parent query
|
||||
)
|
||||
switch axisQuery := firstInput.(type) {
|
||||
case *ancestorQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *attributeQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *childQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *cachedChildQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *descendantQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *followingQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *precedingQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *parentQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *selfQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *groupQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
case *descendantOverDescendantQuery:
|
||||
if _, ok := axisQuery.Input.(*contextQuery); !ok {
|
||||
parent = axisQuery.Input
|
||||
axisQuery.Input = rootQuery
|
||||
}
|
||||
}
|
||||
b.firstInput = nil
|
||||
child := &filterQuery{Input: qyInput, Predicate: cond, NoPosition: false}
|
||||
if parent != nil {
|
||||
return &mergeQuery{Input: parent, Child: child}, nil
|
||||
}
|
||||
return child, nil
|
||||
}
|
||||
b.firstInput = nil
|
||||
}
|
||||
|
||||
resultQuery := &filterQuery{
|
||||
Input: qyInput,
|
||||
Predicate: cond,
|
||||
NoPosition: (propsCond & builderProps.HasPosition) == 0,
|
||||
}
|
||||
return resultQuery, nil
|
||||
}
|
||||
|
||||
// processFunctionNode processes query for the XPath function node.
|
||||
func (b *builder) processFunction(root *functionNode, props *builderProp) (query, error) {
|
||||
// Reset builder props
|
||||
*props = builderProps.None
|
||||
|
||||
var qyOutput query
|
||||
switch root.FuncName {
|
||||
case "lower-case":
|
||||
arg, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: lowerCaseFunc(arg)}
|
||||
case "starts-with":
|
||||
arg1, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
arg2, err := b.processNode(root.Args[1], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: startwithFunc(arg1, arg2)}
|
||||
case "ends-with":
|
||||
arg1, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
arg2, err := b.processNode(root.Args[1], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: endwithFunc(arg1, arg2)}
|
||||
case "contains":
|
||||
arg1, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
arg2, err := b.processNode(root.Args[1], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: containsFunc(arg1, arg2)}
|
||||
case "matches":
|
||||
//matches(string , pattern)
|
||||
if len(root.Args) != 2 {
|
||||
return nil, errors.New("xpath: matches function must have two parameters")
|
||||
}
|
||||
var (
|
||||
arg1, arg2 query
|
||||
err error
|
||||
)
|
||||
if arg1, err = b.processNode(root.Args[0], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if arg2, err = b.processNode(root.Args[1], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Issue #92, testing the regular expression before.
|
||||
if q, ok := arg2.(*constantQuery); ok {
|
||||
if _, err = getRegexp(q.Val.(string)); err != nil {
|
||||
return nil, fmt.Errorf("matches() got error. %v", err)
|
||||
}
|
||||
}
|
||||
qyOutput = &functionQuery{Func: matchesFunc(arg1, arg2)}
|
||||
case "substring":
|
||||
//substring( string , start [, length] )
|
||||
if len(root.Args) < 2 {
|
||||
return nil, errors.New("xpath: substring function must have at least two parameter")
|
||||
}
|
||||
var (
|
||||
arg1, arg2, arg3 query
|
||||
err error
|
||||
)
|
||||
if arg1, err = b.processNode(root.Args[0], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if arg2, err = b.processNode(root.Args[1], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(root.Args) == 3 {
|
||||
if arg3, err = b.processNode(root.Args[2], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
qyOutput = &functionQuery{Func: substringFunc(arg1, arg2, arg3)}
|
||||
case "substring-before", "substring-after":
|
||||
//substring-xxxx( haystack, needle )
|
||||
if len(root.Args) != 2 {
|
||||
return nil, errors.New("xpath: substring-before function must have two parameters")
|
||||
}
|
||||
var (
|
||||
arg1, arg2 query
|
||||
err error
|
||||
)
|
||||
if arg1, err = b.processNode(root.Args[0], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if arg2, err = b.processNode(root.Args[1], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{
|
||||
Func: substringIndFunc(arg1, arg2, root.FuncName == "substring-after"),
|
||||
}
|
||||
case "string-length":
|
||||
// string-length( [string] )
|
||||
if len(root.Args) < 1 {
|
||||
return nil, errors.New("xpath: string-length function must have at least one parameter")
|
||||
}
|
||||
arg1, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: stringLengthFunc(arg1)}
|
||||
case "normalize-space":
|
||||
var arg node
|
||||
if len(root.Args) > 0 {
|
||||
arg = root.Args[0]
|
||||
} else {
|
||||
arg = newAxisNode("self", allNode, "", "", "", nil)
|
||||
}
|
||||
arg1, err := b.processNode(arg, flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: normalizespaceFunc(arg1)}
|
||||
case "replace":
|
||||
//replace( string , string, string )
|
||||
if len(root.Args) != 3 {
|
||||
return nil, errors.New("xpath: replace function must have three parameters")
|
||||
}
|
||||
var (
|
||||
arg1, arg2, arg3 query
|
||||
err error
|
||||
)
|
||||
if arg1, err = b.processNode(root.Args[0], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if arg2, err = b.processNode(root.Args[1], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if arg3, err = b.processNode(root.Args[2], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: replaceFunc(arg1, arg2, arg3)}
|
||||
case "translate":
|
||||
//translate( string , string, string )
|
||||
if len(root.Args) != 3 {
|
||||
return nil, errors.New("xpath: translate function must have three parameters")
|
||||
}
|
||||
var (
|
||||
arg1, arg2, arg3 query
|
||||
err error
|
||||
)
|
||||
if arg1, err = b.processNode(root.Args[0], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if arg2, err = b.processNode(root.Args[1], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if arg3, err = b.processNode(root.Args[2], flagsEnum.None, props); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: translateFunc(arg1, arg2, arg3)}
|
||||
case "not":
|
||||
if len(root.Args) == 0 {
|
||||
return nil, errors.New("xpath: not function must have at least one parameter")
|
||||
}
|
||||
argQuery, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: notFunc(argQuery)}
|
||||
case "name", "local-name", "namespace-uri":
|
||||
if len(root.Args) > 1 {
|
||||
return nil, fmt.Errorf("xpath: %s function must have at most one parameter", root.FuncName)
|
||||
}
|
||||
var (
|
||||
arg query
|
||||
err error
|
||||
)
|
||||
if len(root.Args) == 1 {
|
||||
arg, err = b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
switch root.FuncName {
|
||||
case "name":
|
||||
qyOutput = &functionQuery{Func: nameFunc(arg)}
|
||||
case "local-name":
|
||||
qyOutput = &functionQuery{Func: localNameFunc(arg)}
|
||||
case "namespace-uri":
|
||||
qyOutput = &functionQuery{Func: namespaceFunc(arg)}
|
||||
}
|
||||
case "true", "false":
|
||||
val := root.FuncName == "true"
|
||||
qyOutput = &functionQuery{
|
||||
Func: func(_ query, _ iterator) interface{} {
|
||||
return val
|
||||
},
|
||||
}
|
||||
case "last":
|
||||
qyOutput = &functionQuery{Input: b.firstInput, Func: lastFunc()}
|
||||
*props |= builderProps.HasLast
|
||||
case "position":
|
||||
qyOutput = &functionQuery{Input: b.firstInput, Func: positionFunc()}
|
||||
*props |= builderProps.HasPosition
|
||||
case "boolean", "number", "string":
|
||||
var inp query
|
||||
if len(root.Args) > 1 {
|
||||
return nil, fmt.Errorf("xpath: %s function must have at most one parameter", root.FuncName)
|
||||
}
|
||||
if len(root.Args) == 1 {
|
||||
argQuery, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
inp = argQuery
|
||||
}
|
||||
switch root.FuncName {
|
||||
case "boolean":
|
||||
qyOutput = &functionQuery{Func: booleanFunc(inp)}
|
||||
case "string":
|
||||
qyOutput = &functionQuery{Func: stringFunc(inp)}
|
||||
case "number":
|
||||
qyOutput = &functionQuery{Func: numberFunc(inp)}
|
||||
}
|
||||
case "count":
|
||||
if len(root.Args) == 0 {
|
||||
return nil, fmt.Errorf("xpath: count(node-sets) function must with have parameters node-sets")
|
||||
}
|
||||
argQuery, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: countFunc(argQuery)}
|
||||
case "sum":
|
||||
if len(root.Args) == 0 {
|
||||
return nil, fmt.Errorf("xpath: sum(node-sets) function must with have parameters node-sets")
|
||||
}
|
||||
argQuery, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: sumFunc(argQuery)}
|
||||
case "ceiling", "floor", "round":
|
||||
if len(root.Args) == 0 {
|
||||
return nil, fmt.Errorf("xpath: ceiling(node-sets) function must with have parameters node-sets")
|
||||
}
|
||||
argQuery, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch root.FuncName {
|
||||
case "ceiling":
|
||||
qyOutput = &functionQuery{Func: ceilingFunc(argQuery)}
|
||||
case "floor":
|
||||
qyOutput = &functionQuery{Func: floorFunc(argQuery)}
|
||||
case "round":
|
||||
qyOutput = &functionQuery{Func: roundFunc(argQuery)}
|
||||
}
|
||||
case "concat":
|
||||
if len(root.Args) < 2 {
|
||||
return nil, fmt.Errorf("xpath: concat() must have at least two arguments")
|
||||
}
|
||||
var args []query
|
||||
for _, v := range root.Args {
|
||||
q, err := b.processNode(v, flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args = append(args, q)
|
||||
}
|
||||
qyOutput = &functionQuery{Func: concatFunc(args...)}
|
||||
case "reverse":
|
||||
if len(root.Args) == 0 {
|
||||
return nil, fmt.Errorf("xpath: reverse(node-sets) function must with have parameters node-sets")
|
||||
}
|
||||
argQuery, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &transformFunctionQuery{Input: argQuery, Func: reverseFunc}
|
||||
case "string-join":
|
||||
if len(root.Args) != 2 {
|
||||
return nil, fmt.Errorf("xpath: string-join(node-sets, separator) function requires node-set and argument")
|
||||
}
|
||||
input, err := b.processNode(root.Args[0], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
arg1, err := b.processNode(root.Args[1], flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qyOutput = &functionQuery{Func: stringJoinFunc(input, arg1)}
|
||||
default:
|
||||
return nil, fmt.Errorf("not yet support this function %s()", root.FuncName)
|
||||
}
|
||||
return qyOutput, nil
|
||||
}
|
||||
|
||||
func (b *builder) processOperator(root *operatorNode, props *builderProp) (query, error) {
|
||||
var (
|
||||
leftProp builderProp
|
||||
rightProp builderProp
|
||||
)
|
||||
|
||||
left, err := b.processNode(root.Left, flagsEnum.None, &leftProp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
right, err := b.processNode(root.Right, flagsEnum.None, &rightProp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*props = leftProp | rightProp
|
||||
|
||||
var qyOutput query
|
||||
switch root.Op {
|
||||
case "+", "-", "*", "div", "mod": // Numeric operator
|
||||
var exprFunc func(iterator, interface{}, interface{}) interface{}
|
||||
switch root.Op {
|
||||
case "+":
|
||||
exprFunc = plusFunc
|
||||
case "-":
|
||||
exprFunc = minusFunc
|
||||
case "*":
|
||||
exprFunc = mulFunc
|
||||
case "div":
|
||||
exprFunc = divFunc
|
||||
case "mod":
|
||||
exprFunc = modFunc
|
||||
}
|
||||
qyOutput = &numericQuery{Left: left, Right: right, Do: exprFunc}
|
||||
case "=", ">", ">=", "<", "<=", "!=":
|
||||
var exprFunc func(iterator, interface{}, interface{}) interface{}
|
||||
switch root.Op {
|
||||
case "=":
|
||||
exprFunc = eqFunc
|
||||
case ">":
|
||||
exprFunc = gtFunc
|
||||
case ">=":
|
||||
exprFunc = geFunc
|
||||
case "<":
|
||||
exprFunc = ltFunc
|
||||
case "<=":
|
||||
exprFunc = leFunc
|
||||
case "!=":
|
||||
exprFunc = neFunc
|
||||
}
|
||||
qyOutput = &logicalQuery{Left: left, Right: right, Do: exprFunc}
|
||||
case "or", "and":
|
||||
isOr := false
|
||||
if root.Op == "or" {
|
||||
isOr = true
|
||||
}
|
||||
qyOutput = &booleanQuery{Left: left, Right: right, IsOr: isOr}
|
||||
case "|":
|
||||
*props |= builderProps.NonFlat
|
||||
qyOutput = &unionQuery{Left: left, Right: right}
|
||||
}
|
||||
return qyOutput, nil
|
||||
}
|
||||
|
||||
func (b *builder) processNode(root node, flags flag, props *builderProp) (q query, err error) {
|
||||
if b.parseDepth = b.parseDepth + 1; b.parseDepth > 1024 {
|
||||
err = errors.New("the xpath expressions is too complex")
|
||||
return
|
||||
}
|
||||
*props = builderProps.None
|
||||
switch root.Type() {
|
||||
case nodeConstantOperand:
|
||||
n := root.(*operandNode)
|
||||
q = &constantQuery{Val: n.Val}
|
||||
case nodeRoot:
|
||||
q = &absoluteQuery{}
|
||||
case nodeAxis:
|
||||
q, err = b.processAxis(root.(*axisNode), flags, props)
|
||||
b.firstInput = q
|
||||
case nodeFilter:
|
||||
q, err = b.processFilter(root.(*filterNode), flags, props)
|
||||
b.firstInput = q
|
||||
case nodeFunction:
|
||||
q, err = b.processFunction(root.(*functionNode), props)
|
||||
case nodeOperator:
|
||||
q, err = b.processOperator(root.(*operatorNode), props)
|
||||
case nodeGroup:
|
||||
q, err = b.processNode(root.(*groupNode).Input, flagsEnum.None, props)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
q = &groupQuery{Input: q}
|
||||
if b.firstInput == nil {
|
||||
b.firstInput = q
|
||||
}
|
||||
}
|
||||
b.parseDepth--
|
||||
return
|
||||
}
|
||||
|
||||
// build builds a specified XPath expressions expr.
|
||||
func build(expr string, namespaces map[string]string) (q query, err error) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
switch x := e.(type) {
|
||||
case string:
|
||||
err = errors.New(x)
|
||||
case error:
|
||||
err = x
|
||||
default:
|
||||
err = errors.New("unknown panic")
|
||||
}
|
||||
}
|
||||
}()
|
||||
root := parse(expr, namespaces)
|
||||
b := &builder{}
|
||||
props := builderProps.None
|
||||
return b.processNode(root, flagsEnum.None, &props)
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package xpath
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type loadFunc func(key interface{}) (interface{}, error)
|
||||
|
||||
const (
|
||||
defaultCap = 65536
|
||||
)
|
||||
|
||||
// The reason we're building a simple capacity-resetting loading cache (when capacity reached) instead of using
|
||||
// something like github.com/hashicorp/golang-lru is primarily due to (not wanting to create) external dependency.
|
||||
// Currently this library has 0 external dep (other than go sdk), and supports go 1.6, 1.9, and 1.10 (and later).
|
||||
// Creating external lib dependencies (plus their transitive dependencies) would make things hard if not impossible.
|
||||
// We expect under most circumstances, the defaultCap is big enough for any long running services that use this
|
||||
// library if their xpath regexp cardinality is low. However, in extreme cases when the capacity is reached, we
|
||||
// simply reset the cache, taking a small subsequent perf hit (next to nothing considering amortization) in trade
|
||||
// of more complex and less performant LRU type of construct.
|
||||
type loadingCache struct {
|
||||
sync.RWMutex
|
||||
cap int
|
||||
load loadFunc
|
||||
m map[interface{}]interface{}
|
||||
reset int
|
||||
}
|
||||
|
||||
// NewLoadingCache creates a new instance of a loading cache with capacity. Capacity must be >= 0, or
|
||||
// it will panic. Capacity == 0 means the cache growth is unbounded.
|
||||
func NewLoadingCache(load loadFunc, capacity int) *loadingCache {
|
||||
if capacity < 0 {
|
||||
panic("capacity must be >= 0")
|
||||
}
|
||||
return &loadingCache{cap: capacity, load: load, m: make(map[interface{}]interface{})}
|
||||
}
|
||||
|
||||
func (c *loadingCache) get(key interface{}) (interface{}, error) {
|
||||
c.RLock()
|
||||
v, found := c.m[key]
|
||||
c.RUnlock()
|
||||
if found {
|
||||
return v, nil
|
||||
}
|
||||
v, err := c.load(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Lock()
|
||||
if c.cap > 0 && len(c.m) >= c.cap {
|
||||
c.m = map[interface{}]interface{}{key: v}
|
||||
c.reset++
|
||||
} else {
|
||||
c.m[key] = v
|
||||
}
|
||||
c.Unlock()
|
||||
return v, nil
|
||||
}
|
||||
|
||||
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()
|
||||
)
|
||||
|
||||
func defaultRegexpCache() *loadingCache {
|
||||
return NewLoadingCache(
|
||||
func(key interface{}) (interface{}, error) {
|
||||
return regexp.Compile(key.(string))
|
||||
}, defaultCap)
|
||||
}
|
||||
|
||||
func getRegexp(pattern string) (*regexp.Regexp, error) {
|
||||
exp, err := RegexpCache.get(pattern)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return exp.(*regexp.Regexp), nil
|
||||
}
|
||||
+679
@@ -0,0 +1,679 @@
|
||||
package xpath
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Defined an interface of stringBuilder that compatible with
|
||||
// strings.Builder(go 1.10) and bytes.Buffer(< go 1.10)
|
||||
type stringBuilder interface {
|
||||
WriteRune(r rune) (n int, err error)
|
||||
WriteString(s string) (int, error)
|
||||
Reset()
|
||||
Grow(n int)
|
||||
String() string
|
||||
}
|
||||
|
||||
var builderPool = sync.Pool{New: func() interface{} {
|
||||
return newStringBuilder()
|
||||
}}
|
||||
|
||||
// The XPath function list.
|
||||
|
||||
func predicate(q query) func(NodeNavigator) bool {
|
||||
type Predicater interface {
|
||||
Test(NodeNavigator) bool
|
||||
}
|
||||
if p, ok := q.(Predicater); ok {
|
||||
return p.Test
|
||||
}
|
||||
return func(NodeNavigator) bool { return true }
|
||||
}
|
||||
|
||||
// positionFunc is a XPath Node Set functions position().
|
||||
func positionFunc() func(query, iterator) interface{} {
|
||||
return func(q query, t iterator) interface{} {
|
||||
var (
|
||||
count = 1
|
||||
node = t.Current().Copy()
|
||||
)
|
||||
test := predicate(q)
|
||||
for node.MoveToPrevious() {
|
||||
if test(node) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return float64(count)
|
||||
}
|
||||
}
|
||||
|
||||
// lastFunc is a XPath Node Set functions last().
|
||||
func lastFunc() func(query, iterator) interface{} {
|
||||
return func(q query, t iterator) interface{} {
|
||||
var (
|
||||
count = 0
|
||||
node = t.Current().Copy()
|
||||
)
|
||||
test := predicate(q)
|
||||
node.MoveToFirst()
|
||||
for {
|
||||
if test(node) {
|
||||
count++
|
||||
}
|
||||
if !node.MoveToNext() {
|
||||
break
|
||||
}
|
||||
}
|
||||
return float64(count)
|
||||
}
|
||||
}
|
||||
|
||||
// countFunc is a XPath Node Set functions count(node-set).
|
||||
func countFunc(arg query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var count = 0
|
||||
q := functionArgs(arg)
|
||||
test := predicate(q)
|
||||
switch typ := q.Evaluate(t).(type) {
|
||||
case query:
|
||||
for node := typ.Select(t); node != nil; node = typ.Select(t) {
|
||||
if test(node) {
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
return float64(count)
|
||||
}
|
||||
}
|
||||
|
||||
// sumFunc is a XPath Node Set functions sum(node-set).
|
||||
func sumFunc(arg query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var sum float64
|
||||
switch typ := functionArgs(arg).Evaluate(t).(type) {
|
||||
case query:
|
||||
for node := typ.Select(t); node != nil; node = typ.Select(t) {
|
||||
if v, err := strconv.ParseFloat(node.Value(), 64); err == nil {
|
||||
sum += v
|
||||
}
|
||||
}
|
||||
case float64:
|
||||
sum = typ
|
||||
case string:
|
||||
v, err := strconv.ParseFloat(typ, 64)
|
||||
if err != nil {
|
||||
panic(errors.New("sum() function argument type must be a node-set or number"))
|
||||
}
|
||||
sum = v
|
||||
}
|
||||
return sum
|
||||
}
|
||||
}
|
||||
|
||||
func asNumber(t iterator, o interface{}) float64 {
|
||||
switch typ := o.(type) {
|
||||
case query:
|
||||
node := typ.Select(t)
|
||||
if node == nil {
|
||||
return math.NaN()
|
||||
}
|
||||
if v, err := strconv.ParseFloat(node.Value(), 64); err == nil {
|
||||
return v
|
||||
}
|
||||
case float64:
|
||||
return typ
|
||||
case string:
|
||||
v, err := strconv.ParseFloat(typ, 64)
|
||||
if err == nil {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return math.NaN()
|
||||
}
|
||||
|
||||
// ceilingFunc is a XPath Node Set functions ceiling(node-set).
|
||||
func ceilingFunc(arg query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
val := asNumber(t, functionArgs(arg).Evaluate(t))
|
||||
// if math.IsNaN(val) {
|
||||
// panic(errors.New("ceiling() function argument type must be a valid number"))
|
||||
// }
|
||||
return math.Ceil(val)
|
||||
}
|
||||
}
|
||||
|
||||
// floorFunc is a XPath Node Set functions floor(node-set).
|
||||
func floorFunc(arg query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
val := asNumber(t, functionArgs(arg).Evaluate(t))
|
||||
return math.Floor(val)
|
||||
}
|
||||
}
|
||||
|
||||
// roundFunc is a XPath Node Set functions round(node-set).
|
||||
func roundFunc(arg query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
val := asNumber(t, functionArgs(arg).Evaluate(t))
|
||||
//return math.Round(val)
|
||||
return round(val)
|
||||
}
|
||||
}
|
||||
|
||||
// nameFunc is a XPath functions name([node-set]).
|
||||
func nameFunc(arg query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var v NodeNavigator
|
||||
if arg == nil {
|
||||
v = t.Current()
|
||||
} else {
|
||||
v = arg.Clone().Select(t)
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
ns := v.Prefix()
|
||||
if ns == "" {
|
||||
return v.LocalName()
|
||||
}
|
||||
return ns + ":" + v.LocalName()
|
||||
}
|
||||
}
|
||||
|
||||
// localNameFunc is a XPath functions local-name([node-set]).
|
||||
func localNameFunc(arg query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var v NodeNavigator
|
||||
if arg == nil {
|
||||
v = t.Current()
|
||||
} else {
|
||||
v = arg.Clone().Select(t)
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return v.LocalName()
|
||||
}
|
||||
}
|
||||
|
||||
// namespaceFunc is a XPath functions namespace-uri([node-set]).
|
||||
func namespaceFunc(arg query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var v NodeNavigator
|
||||
if arg == nil {
|
||||
v = t.Current()
|
||||
} else {
|
||||
// Get the first node in the node-set if specified.
|
||||
v = arg.Clone().Select(t)
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
// fix about namespace-uri() bug: https://github.com/antchfx/xmlquery/issues/22
|
||||
// TODO: In the next version, add NamespaceURL() to the NodeNavigator interface.
|
||||
type namespaceURL interface {
|
||||
NamespaceURL() string
|
||||
}
|
||||
if f, ok := v.(namespaceURL); ok {
|
||||
return f.NamespaceURL()
|
||||
}
|
||||
return v.Prefix()
|
||||
}
|
||||
}
|
||||
|
||||
func asBool(t iterator, v interface{}) bool {
|
||||
switch v := v.(type) {
|
||||
case nil:
|
||||
return false
|
||||
case *NodeIterator:
|
||||
return v.MoveNext()
|
||||
case bool:
|
||||
return v
|
||||
case float64:
|
||||
return v != 0
|
||||
case string:
|
||||
return v != ""
|
||||
case query:
|
||||
return v.Select(t) != nil
|
||||
default:
|
||||
panic(fmt.Errorf("unexpected type: %T", v))
|
||||
}
|
||||
}
|
||||
|
||||
func asString(t iterator, v interface{}) string {
|
||||
switch v := v.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case bool:
|
||||
if v {
|
||||
return "true"
|
||||
}
|
||||
return "false"
|
||||
case float64:
|
||||
return strconv.FormatFloat(v, 'g', -1, 64)
|
||||
case string:
|
||||
return v
|
||||
case query:
|
||||
node := v.Select(t)
|
||||
if node == nil {
|
||||
return ""
|
||||
}
|
||||
return node.Value()
|
||||
default:
|
||||
panic(fmt.Errorf("unexpected type: %T", v))
|
||||
}
|
||||
}
|
||||
|
||||
// booleanFunc is a XPath functions boolean([node-set]).
|
||||
func booleanFunc(arg1 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
v := functionArgs(arg1).Evaluate(t)
|
||||
return asBool(t, v)
|
||||
}
|
||||
}
|
||||
|
||||
// numberFunc is a XPath functions number([node-set]).
|
||||
func numberFunc(arg1 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
v := functionArgs(arg1).Evaluate(t)
|
||||
return asNumber(t, v)
|
||||
}
|
||||
}
|
||||
|
||||
// stringFunc is a XPath functions string([node-set]).
|
||||
func stringFunc(arg1 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
v := functionArgs(arg1).Evaluate(t)
|
||||
return asString(t, v)
|
||||
}
|
||||
}
|
||||
|
||||
// startwithFunc is a XPath functions starts-with(string, string).
|
||||
func startwithFunc(arg1, arg2 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var (
|
||||
m, n string
|
||||
ok bool
|
||||
)
|
||||
switch typ := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
m = typ
|
||||
case query:
|
||||
node := typ.Select(t)
|
||||
if node == nil {
|
||||
return false
|
||||
}
|
||||
m = node.Value()
|
||||
default:
|
||||
panic(errors.New("starts-with() function argument type must be string"))
|
||||
}
|
||||
n, ok = functionArgs(arg2).Evaluate(t).(string)
|
||||
if !ok {
|
||||
panic(errors.New("starts-with() function argument type must be string"))
|
||||
}
|
||||
return strings.HasPrefix(m, n)
|
||||
}
|
||||
}
|
||||
|
||||
// endwithFunc is a XPath functions ends-with(string, string).
|
||||
func endwithFunc(arg1, arg2 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var (
|
||||
m, n string
|
||||
ok bool
|
||||
)
|
||||
switch typ := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
m = typ
|
||||
case query:
|
||||
node := typ.Select(t)
|
||||
if node == nil {
|
||||
return false
|
||||
}
|
||||
m = node.Value()
|
||||
default:
|
||||
panic(errors.New("ends-with() function argument type must be string"))
|
||||
}
|
||||
n, ok = functionArgs(arg2).Evaluate(t).(string)
|
||||
if !ok {
|
||||
panic(errors.New("ends-with() function argument type must be string"))
|
||||
}
|
||||
return strings.HasSuffix(m, n)
|
||||
}
|
||||
}
|
||||
|
||||
// containsFunc is a XPath functions contains(string or @attr, string).
|
||||
func containsFunc(arg1, arg2 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var (
|
||||
m, n string
|
||||
ok bool
|
||||
)
|
||||
switch typ := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
m = typ
|
||||
case query:
|
||||
node := typ.Select(t)
|
||||
if node == nil {
|
||||
return false
|
||||
}
|
||||
m = node.Value()
|
||||
default:
|
||||
panic(errors.New("contains() function argument type must be string"))
|
||||
}
|
||||
|
||||
n, ok = functionArgs(arg2).Evaluate(t).(string)
|
||||
if !ok {
|
||||
panic(errors.New("contains() function argument type must be string"))
|
||||
}
|
||||
|
||||
return strings.Contains(m, n)
|
||||
}
|
||||
}
|
||||
|
||||
// matchesFunc is an XPath function that tests a given string against a regexp pattern.
|
||||
// Note: does not support https://www.w3.org/TR/xpath-functions-31/#func-matches 3rd optional `flags` argument; if
|
||||
// needed, directly put flags in the regexp pattern, such as `(?i)^pattern$` for `i` flag.
|
||||
func matchesFunc(arg1, arg2 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var s string
|
||||
switch typ := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
s = typ
|
||||
case query:
|
||||
node := typ.Select(t)
|
||||
if node == nil {
|
||||
return ""
|
||||
}
|
||||
s = node.Value()
|
||||
}
|
||||
var pattern string
|
||||
var ok bool
|
||||
if pattern, ok = functionArgs(arg2).Evaluate(t).(string); !ok {
|
||||
panic(errors.New("matches() function second argument type must be string"))
|
||||
}
|
||||
re, err := getRegexp(pattern)
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("matches() function second argument is not a valid regexp pattern, err: %s", err.Error()))
|
||||
}
|
||||
return re.MatchString(s)
|
||||
}
|
||||
}
|
||||
|
||||
// normalizespaceFunc is XPath functions normalize-space(string?)
|
||||
func normalizespaceFunc(arg1 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var m string
|
||||
switch typ := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
m = typ
|
||||
case query:
|
||||
node := typ.Select(t)
|
||||
if node == nil {
|
||||
return ""
|
||||
}
|
||||
m = node.Value()
|
||||
}
|
||||
var b = builderPool.Get().(stringBuilder)
|
||||
b.Grow(len(m))
|
||||
|
||||
runeStr := []rune(strings.TrimSpace(m))
|
||||
l := len(runeStr)
|
||||
for i := range runeStr {
|
||||
r := runeStr[i]
|
||||
isSpace := unicode.IsSpace(r)
|
||||
if !(isSpace && (i+1 < l && unicode.IsSpace(runeStr[i+1]))) {
|
||||
if isSpace {
|
||||
r = ' '
|
||||
}
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
result := b.String()
|
||||
b.Reset()
|
||||
builderPool.Put(b)
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
// substringFunc is XPath functions substring function returns a part of a given string.
|
||||
func substringFunc(arg1, arg2, arg3 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var m string
|
||||
switch typ := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
m = typ
|
||||
case query:
|
||||
node := typ.Select(t)
|
||||
if node == nil {
|
||||
return ""
|
||||
}
|
||||
m = node.Value()
|
||||
}
|
||||
|
||||
var start, length float64
|
||||
var ok bool
|
||||
|
||||
if start, ok = functionArgs(arg2).Evaluate(t).(float64); !ok {
|
||||
panic(errors.New("substring() function first argument type must be int"))
|
||||
} else if start < 1 {
|
||||
panic(errors.New("substring() function first argument type must be >= 1"))
|
||||
}
|
||||
start--
|
||||
if arg3 != nil {
|
||||
if length, ok = functionArgs(arg3).Evaluate(t).(float64); !ok {
|
||||
panic(errors.New("substring() function second argument type must be int"))
|
||||
}
|
||||
}
|
||||
if (len(m) - int(start)) < int(length) {
|
||||
panic(errors.New("substring() function start and length argument out of range"))
|
||||
}
|
||||
if length > 0 {
|
||||
return m[int(start):int(length+start)]
|
||||
}
|
||||
return m[int(start):]
|
||||
}
|
||||
}
|
||||
|
||||
// substringIndFunc is XPath functions substring-before/substring-after function returns a part of a given string.
|
||||
func substringIndFunc(arg1, arg2 query, after bool) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var str string
|
||||
switch v := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
str = v
|
||||
case query:
|
||||
node := v.Select(t)
|
||||
if node == nil {
|
||||
return ""
|
||||
}
|
||||
str = node.Value()
|
||||
}
|
||||
var word string
|
||||
switch v := functionArgs(arg2).Evaluate(t).(type) {
|
||||
case string:
|
||||
word = v
|
||||
case query:
|
||||
node := v.Select(t)
|
||||
if node == nil {
|
||||
return ""
|
||||
}
|
||||
word = node.Value()
|
||||
}
|
||||
if word == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
i := strings.Index(str, word)
|
||||
if i < 0 {
|
||||
return ""
|
||||
}
|
||||
if after {
|
||||
return str[i+len(word):]
|
||||
}
|
||||
return str[:i]
|
||||
}
|
||||
}
|
||||
|
||||
// stringLengthFunc is XPATH string-length( [string] ) function that returns a number
|
||||
// equal to the number of characters in a given string.
|
||||
func stringLengthFunc(arg1 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
switch v := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
return float64(len(v))
|
||||
case query:
|
||||
node := v.Select(t)
|
||||
if node == nil {
|
||||
break
|
||||
}
|
||||
return float64(len(node.Value()))
|
||||
}
|
||||
return float64(0)
|
||||
}
|
||||
}
|
||||
|
||||
// translateFunc is XPath functions translate() function returns a replaced string.
|
||||
func translateFunc(arg1, arg2, arg3 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
str := asString(t, functionArgs(arg1).Evaluate(t))
|
||||
src := asString(t, functionArgs(arg2).Evaluate(t))
|
||||
dst := asString(t, functionArgs(arg3).Evaluate(t))
|
||||
|
||||
replace := make([]string, 0, len(src))
|
||||
for i, s := range src {
|
||||
d := ""
|
||||
if i < len(dst) {
|
||||
d = string(dst[i])
|
||||
}
|
||||
replace = append(replace, string(s), d)
|
||||
}
|
||||
return strings.NewReplacer(replace...).Replace(str)
|
||||
}
|
||||
}
|
||||
|
||||
// replaceFunc is XPath functions replace() function returns a replaced string.
|
||||
func replaceFunc(arg1, arg2, arg3 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
str := asString(t, functionArgs(arg1).Evaluate(t))
|
||||
src := asString(t, functionArgs(arg2).Evaluate(t))
|
||||
dst := asString(t, functionArgs(arg3).Evaluate(t))
|
||||
|
||||
return strings.Replace(str, src, dst, -1)
|
||||
}
|
||||
}
|
||||
|
||||
// notFunc is XPATH functions not(expression) function operation.
|
||||
func notFunc(arg1 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
switch v := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case bool:
|
||||
return !v
|
||||
case query:
|
||||
node := v.Select(t)
|
||||
return node == nil
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// concatFunc is the concat function concatenates two or more
|
||||
// strings and returns the resulting string.
|
||||
// concat( string1 , string2 [, stringn]* )
|
||||
func concatFunc(args ...query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
b := builderPool.Get().(stringBuilder)
|
||||
for _, v := range args {
|
||||
v = functionArgs(v)
|
||||
|
||||
switch v := v.Evaluate(t).(type) {
|
||||
case string:
|
||||
b.WriteString(v)
|
||||
case query:
|
||||
node := v.Select(t)
|
||||
if node != nil {
|
||||
b.WriteString(node.Value())
|
||||
}
|
||||
}
|
||||
}
|
||||
result := b.String()
|
||||
b.Reset()
|
||||
builderPool.Put(b)
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
// https://github.com/antchfx/xpath/issues/43
|
||||
func functionArgs(q query) query {
|
||||
if _, ok := q.(*functionQuery); ok {
|
||||
return q
|
||||
}
|
||||
return q.Clone()
|
||||
}
|
||||
|
||||
func reverseFunc(q query, t iterator) func() NodeNavigator {
|
||||
var list []NodeNavigator
|
||||
for {
|
||||
node := q.Select(t)
|
||||
if node == nil {
|
||||
break
|
||||
}
|
||||
list = append(list, node.Copy())
|
||||
}
|
||||
i := len(list)
|
||||
return func() NodeNavigator {
|
||||
if i <= 0 {
|
||||
return nil
|
||||
}
|
||||
i--
|
||||
node := list[i]
|
||||
return node
|
||||
}
|
||||
}
|
||||
|
||||
// string-join is a XPath Node Set functions string-join(node-set, separator).
|
||||
func stringJoinFunc(q, arg1 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
var separator string
|
||||
switch v := functionArgs(arg1).Evaluate(t).(type) {
|
||||
case string:
|
||||
separator = v
|
||||
case query:
|
||||
node := v.Select(t)
|
||||
if node != nil {
|
||||
separator = node.Value()
|
||||
}
|
||||
}
|
||||
|
||||
q = functionArgs(q)
|
||||
test := predicate(q)
|
||||
var parts []string
|
||||
switch v := q.Evaluate(t).(type) {
|
||||
case string:
|
||||
return v
|
||||
case query:
|
||||
for node := v.Select(t); node != nil; node = v.Select(t) {
|
||||
if test(node) {
|
||||
parts = append(parts, node.Value())
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, separator)
|
||||
}
|
||||
}
|
||||
|
||||
// lower-case is XPATH function that converts a string to lower case.
|
||||
func lowerCaseFunc(arg1 query) func(query, iterator) interface{} {
|
||||
return func(_ query, t iterator) interface{} {
|
||||
v := functionArgs(arg1).Evaluate(t)
|
||||
return strings.ToLower(asString(t, v))
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// +build go1.10
|
||||
|
||||
package xpath
|
||||
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func round(f float64) int {
|
||||
return int(math.Round(f))
|
||||
}
|
||||
|
||||
func newStringBuilder() stringBuilder {
|
||||
return &strings.Builder{}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
// +build !go1.10
|
||||
|
||||
package xpath
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math"
|
||||
)
|
||||
|
||||
// math.Round() is supported by Go 1.10+,
|
||||
// This method just compatible for version <1.10.
|
||||
// https://github.com/golang/go/issues/20100
|
||||
func round(f float64) int {
|
||||
if math.Abs(f) < 0.5 {
|
||||
return 0
|
||||
}
|
||||
return int(f + math.Copysign(0.5, f))
|
||||
}
|
||||
|
||||
func newStringBuilder() stringBuilder {
|
||||
return &bytes.Buffer{}
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
package xpath
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// The XPath number operator function list.
|
||||
|
||||
type logical func(iterator, string, interface{}, interface{}) bool
|
||||
|
||||
var logicalFuncs = [][]logical{
|
||||
{cmpBooleanBoolean, nil, nil, nil},
|
||||
{nil, cmpNumericNumeric, cmpNumericString, cmpNumericNodeSet},
|
||||
{nil, cmpStringNumeric, cmpStringString, cmpStringNodeSet},
|
||||
{nil, cmpNodeSetNumeric, cmpNodeSetString, cmpNodeSetNodeSet},
|
||||
}
|
||||
|
||||
// number vs number
|
||||
func cmpNumberNumberF(op string, a, b float64) bool {
|
||||
switch op {
|
||||
case "=":
|
||||
return a == b
|
||||
case ">":
|
||||
return a > b
|
||||
case "<":
|
||||
return a < b
|
||||
case ">=":
|
||||
return a >= b
|
||||
case "<=":
|
||||
return a <= b
|
||||
case "!=":
|
||||
return a != b
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// string vs string
|
||||
func cmpStringStringF(op string, a, b string) bool {
|
||||
switch op {
|
||||
case "=":
|
||||
return a == b
|
||||
case ">":
|
||||
return a > b
|
||||
case "<":
|
||||
return a < b
|
||||
case ">=":
|
||||
return a >= b
|
||||
case "<=":
|
||||
return a <= b
|
||||
case "!=":
|
||||
return a != b
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cmpBooleanBooleanF(op string, a, b bool) bool {
|
||||
switch op {
|
||||
case "or":
|
||||
return a || b
|
||||
case "and":
|
||||
return a && b
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cmpNumericNumeric(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(float64)
|
||||
b := n.(float64)
|
||||
return cmpNumberNumberF(op, a, b)
|
||||
}
|
||||
|
||||
func cmpNumericString(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(float64)
|
||||
b := n.(string)
|
||||
num, err := strconv.ParseFloat(b, 64)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return cmpNumberNumberF(op, a, num)
|
||||
}
|
||||
|
||||
func cmpNumericNodeSet(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(float64)
|
||||
b := n.(query)
|
||||
|
||||
for {
|
||||
node := b.Select(t)
|
||||
if node == nil {
|
||||
break
|
||||
}
|
||||
num, err := strconv.ParseFloat(node.Value(), 64)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if cmpNumberNumberF(op, a, num) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cmpNodeSetNumeric(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(query)
|
||||
b := n.(float64)
|
||||
for {
|
||||
node := a.Select(t)
|
||||
if node == nil {
|
||||
break
|
||||
}
|
||||
num, err := strconv.ParseFloat(node.Value(), 64)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if cmpNumberNumberF(op, num, b) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cmpNodeSetString(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(query)
|
||||
b := n.(string)
|
||||
for {
|
||||
node := a.Select(t)
|
||||
if node == nil {
|
||||
break
|
||||
}
|
||||
if cmpStringStringF(op, b, node.Value()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cmpNodeSetNodeSet(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(query)
|
||||
b := n.(query)
|
||||
for {
|
||||
x := a.Select(t)
|
||||
if x == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
y := b.Select(t)
|
||||
if y == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for {
|
||||
if cmpStringStringF(op, x.Value(), y.Value()) {
|
||||
return true
|
||||
}
|
||||
if y = b.Select(t); y == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
// reset
|
||||
b.Evaluate(t)
|
||||
}
|
||||
}
|
||||
|
||||
func cmpStringNumeric(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(string)
|
||||
b := n.(float64)
|
||||
num, err := strconv.ParseFloat(a, 64)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return cmpNumberNumberF(op, b, num)
|
||||
}
|
||||
|
||||
func cmpStringString(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(string)
|
||||
b := n.(string)
|
||||
return cmpStringStringF(op, a, b)
|
||||
}
|
||||
|
||||
func cmpStringNodeSet(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(string)
|
||||
b := n.(query)
|
||||
for {
|
||||
node := b.Select(t)
|
||||
if node == nil {
|
||||
break
|
||||
}
|
||||
if cmpStringStringF(op, a, node.Value()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cmpBooleanBoolean(t iterator, op string, m, n interface{}) bool {
|
||||
a := m.(bool)
|
||||
b := n.(bool)
|
||||
return cmpBooleanBooleanF(op, a, b)
|
||||
}
|
||||
|
||||
// eqFunc is an `=` operator.
|
||||
func eqFunc(t iterator, m, n interface{}) interface{} {
|
||||
t1 := getXPathType(m)
|
||||
t2 := getXPathType(n)
|
||||
return logicalFuncs[t1][t2](t, "=", m, n)
|
||||
}
|
||||
|
||||
// gtFunc is an `>` operator.
|
||||
func gtFunc(t iterator, m, n interface{}) interface{} {
|
||||
t1 := getXPathType(m)
|
||||
t2 := getXPathType(n)
|
||||
return logicalFuncs[t1][t2](t, ">", m, n)
|
||||
}
|
||||
|
||||
// geFunc is an `>=` operator.
|
||||
func geFunc(t iterator, m, n interface{}) interface{} {
|
||||
t1 := getXPathType(m)
|
||||
t2 := getXPathType(n)
|
||||
return logicalFuncs[t1][t2](t, ">=", m, n)
|
||||
}
|
||||
|
||||
// ltFunc is an `<` operator.
|
||||
func ltFunc(t iterator, m, n interface{}) interface{} {
|
||||
t1 := getXPathType(m)
|
||||
t2 := getXPathType(n)
|
||||
return logicalFuncs[t1][t2](t, "<", m, n)
|
||||
}
|
||||
|
||||
// leFunc is an `<=` operator.
|
||||
func leFunc(t iterator, m, n interface{}) interface{} {
|
||||
t1 := getXPathType(m)
|
||||
t2 := getXPathType(n)
|
||||
return logicalFuncs[t1][t2](t, "<=", m, n)
|
||||
}
|
||||
|
||||
// neFunc is an `!=` operator.
|
||||
func neFunc(t iterator, m, n interface{}) interface{} {
|
||||
t1 := getXPathType(m)
|
||||
t2 := getXPathType(n)
|
||||
return logicalFuncs[t1][t2](t, "!=", m, n)
|
||||
}
|
||||
|
||||
// orFunc is an `or` operator.
|
||||
var orFunc = func(t iterator, m, n interface{}) interface{} {
|
||||
t1 := getXPathType(m)
|
||||
t2 := getXPathType(n)
|
||||
return logicalFuncs[t1][t2](t, "or", m, n)
|
||||
}
|
||||
|
||||
func numericExpr(t iterator, m, n interface{}, cb func(float64, float64) float64) float64 {
|
||||
a := asNumber(t, m)
|
||||
b := asNumber(t, n)
|
||||
return cb(a, b)
|
||||
}
|
||||
|
||||
// plusFunc is an `+` operator.
|
||||
var plusFunc = func(t iterator, m, n interface{}) interface{} {
|
||||
return numericExpr(t, m, n, func(a, b float64) float64 {
|
||||
return a + b
|
||||
})
|
||||
}
|
||||
|
||||
// minusFunc is an `-` operator.
|
||||
var minusFunc = func(t iterator, m, n interface{}) interface{} {
|
||||
return numericExpr(t, m, n, func(a, b float64) float64 {
|
||||
return a - b
|
||||
})
|
||||
}
|
||||
|
||||
// mulFunc is an `*` operator.
|
||||
var mulFunc = func(t iterator, m, n interface{}) interface{} {
|
||||
return numericExpr(t, m, n, func(a, b float64) float64 {
|
||||
return a * b
|
||||
})
|
||||
}
|
||||
|
||||
// divFunc is an `DIV` operator.
|
||||
var divFunc = func(t iterator, m, n interface{}) interface{} {
|
||||
return numericExpr(t, m, n, func(a, b float64) float64 {
|
||||
return a / b
|
||||
})
|
||||
}
|
||||
|
||||
// modFunc is an 'MOD' operator.
|
||||
var modFunc = func(t iterator, m, n interface{}) interface{} {
|
||||
return numericExpr(t, m, n, func(a, b float64) float64 {
|
||||
return float64(int(a) % int(b))
|
||||
})
|
||||
}
|
||||
+1254
File diff suppressed because it is too large
Load Diff
+1437
File diff suppressed because it is too large
Load Diff
+176
@@ -0,0 +1,176 @@
|
||||
package xpath
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// NodeType represents a type of XPath node.
|
||||
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 <element>.
|
||||
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 <!-- my comment -->
|
||||
CommentNode
|
||||
|
||||
// allNode is any types of node, used by xpath package only to predicate match.
|
||||
allNode
|
||||
)
|
||||
|
||||
// NodeNavigator provides cursor model for navigating XML data.
|
||||
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 holds all matched Node object.
|
||||
type NodeIterator struct {
|
||||
node NodeNavigator
|
||||
query query
|
||||
}
|
||||
|
||||
// Current returns current node which matched.
|
||||
func (t *NodeIterator) Current() NodeNavigator {
|
||||
return t.node
|
||||
}
|
||||
|
||||
// MoveNext moves Navigator to the next match node.
|
||||
func (t *NodeIterator) MoveNext() bool {
|
||||
n := t.query.Select(t)
|
||||
if n == nil {
|
||||
return false
|
||||
}
|
||||
if !t.node.MoveTo(n) {
|
||||
t.node = n.Copy()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Select selects a node set using the specified XPath expression.
|
||||
// This method is deprecated, recommend using Expr.Select() method instead.
|
||||
func Select(root NodeNavigator, expr string) *NodeIterator {
|
||||
exp, err := Compile(expr)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exp.Select(root)
|
||||
}
|
||||
|
||||
// Expr is an XPath expression for query.
|
||||
type Expr struct {
|
||||
s string
|
||||
q query
|
||||
}
|
||||
|
||||
type iteratorFunc func() NodeNavigator
|
||||
|
||||
func (f iteratorFunc) Current() NodeNavigator {
|
||||
return f()
|
||||
}
|
||||
|
||||
// Evaluate returns the result of the expression.
|
||||
// The result type of the expression is one of the follow: bool,float64,string,NodeIterator).
|
||||
func (expr *Expr) Evaluate(root NodeNavigator) interface{} {
|
||||
val := expr.q.Evaluate(iteratorFunc(func() NodeNavigator { return root }))
|
||||
switch val.(type) {
|
||||
case query:
|
||||
return &NodeIterator{query: expr.q.Clone(), node: root}
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
// Select selects a node set using the specified XPath expression.
|
||||
func (expr *Expr) Select(root NodeNavigator) *NodeIterator {
|
||||
return &NodeIterator{query: expr.q.Clone(), node: root}
|
||||
}
|
||||
|
||||
// String returns XPath expression string.
|
||||
func (expr *Expr) String() string {
|
||||
return expr.s
|
||||
}
|
||||
|
||||
// Compile compiles an XPath expression string.
|
||||
func Compile(expr string) (*Expr, error) {
|
||||
if expr == "" {
|
||||
return nil, errors.New("expr expression is nil")
|
||||
}
|
||||
qy, err := build(expr, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if qy == nil {
|
||||
return nil, fmt.Errorf(fmt.Sprintf("undeclared variable in XPath expression: %s", expr))
|
||||
}
|
||||
return &Expr{s: expr, q: qy}, nil
|
||||
}
|
||||
|
||||
// MustCompile compiles an XPath expression string and ignored error.
|
||||
func MustCompile(expr string) *Expr {
|
||||
exp, err := Compile(expr)
|
||||
if err != nil {
|
||||
return &Expr{s: expr, q: nopQuery{}}
|
||||
}
|
||||
return exp
|
||||
}
|
||||
|
||||
// CompileWithNS compiles an XPath expression string, using given namespaces map.
|
||||
func CompileWithNS(expr string, namespaces map[string]string) (*Expr, error) {
|
||||
if expr == "" {
|
||||
return nil, errors.New("expr expression is nil")
|
||||
}
|
||||
qy, err := build(expr, namespaces)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if qy == nil {
|
||||
return nil, fmt.Errorf(fmt.Sprintf("undeclared variable in XPath expression: %s", expr))
|
||||
}
|
||||
return &Expr{s: expr, q: qy}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user