Skip to content

Commit

Permalink
#98. remove the duplicate elements filter, avoid htmlquery and `xml…
Browse files Browse the repository at this point in the history
…query` packages re-use the cached element in some cases. #94
  • Loading branch information
zhengchun committed Jun 23, 2024
1 parent 4b4638b commit 5481aef
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 19 deletions.
27 changes: 9 additions & 18 deletions xpath.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ type NodeNavigator interface {
type NodeIterator struct {
node NodeNavigator
query query
table map[uint64]bool
}

// Current returns current node which matched.
Expand All @@ -84,22 +83,14 @@ func (t *NodeIterator) Current() NodeNavigator {

// MoveNext moves Navigator to the next match node.
func (t *NodeIterator) MoveNext() bool {
for {
n := t.query.Select(t)
if n == nil {
return false
}
if !t.node.MoveTo(n) {
t.node = n.Copy()
}
// https://github.com/antchfx/xpath/issues/94
id := getHashCode(n.Copy())
if _, ok := t.table[id]; ok {
continue
}
t.table[id] = true
return true
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.
Expand Down Expand Up @@ -130,14 +121,14 @@ 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, table: make(map[uint64]bool)}
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, table: make(map[uint64]bool)}
return &NodeIterator{query: expr.q.Clone(), node: root}
}

// String returns XPath expression string.
Expand Down
12 changes: 11 additions & 1 deletion xpath_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,17 @@ func selectNode(root *TNode, expr string) *TNode {

func selectNodes(root *TNode, expr string) []*TNode {
t := Select(createNavigator(root), expr)
return iterateNodes(t)
c := make(map[uint64]bool)
var list []*TNode
for _, n := range iterateNodes(t) {
m := getHashCode(createNavigator(n))
if _, ok := c[m]; ok {
continue
}
c[m] = true
list = append(list, n)
}
return list
}

func joinValues(nodes []*TNode) string {
Expand Down

0 comments on commit 5481aef

Please sign in to comment.