@@ -13,33 +13,61 @@ func CreateXPathNavigator(top *Node) *NodeNavigator {
13
13
return & NodeNavigator {cur : top , root : top }
14
14
}
15
15
16
- // Find searches the Node that matches by the specified XPath expr .
16
+ // Find is like QueryAll but will panics if `expr` cannot be parsed .
17
17
func Find (top * Node , expr string ) []* Node {
18
- exp , err := xpath . Compile ( expr )
18
+ nodes , err := QueryAll ( top , expr )
19
19
if err != nil {
20
20
panic (err )
21
21
}
22
- t := exp .Select (CreateXPathNavigator (top ))
23
- var elems []* Node
24
- for t .MoveNext () {
25
- elems = append (elems , (t .Current ().(* NodeNavigator )).cur )
22
+ return nodes
23
+ }
24
+
25
+ // FindOne is like Query but will panics if `expr` cannot be parsed.
26
+ func FindOne (top * Node , expr string ) * Node {
27
+ node , err := Query (top , expr )
28
+ if err != nil {
29
+ panic (err )
26
30
}
27
- return elems
31
+ return node
32
+ }
33
+
34
+ // QueryAll searches the Node that matches by the specified XPath expr.
35
+ // Return an error if the expression `expr` cannot be parsed.
36
+ func QueryAll (top * Node , expr string ) ([]* Node , error ) {
37
+ exp , err := xpath .Compile (expr )
38
+ if err != nil {
39
+ return nil , err
40
+ }
41
+ return QuerySelectorAll (top , exp ), nil
28
42
}
29
43
30
- // FindOne searches the Node that matches by the specified XPath expr,
44
+ // Query searches the Node that matches by the specified XPath expr,
31
45
// and returns first element of matched.
32
- func FindOne (top * Node , expr string ) * Node {
46
+ func Query (top * Node , expr string ) ( * Node , error ) {
33
47
exp , err := xpath .Compile (expr )
34
48
if err != nil {
35
- panic ( err )
49
+ return nil , err
36
50
}
37
- t := exp .Select (CreateXPathNavigator (top ))
38
- var elem * Node
51
+ return QuerySelector (top , exp ), nil
52
+ }
53
+
54
+ // QuerySelectorAll searches all of the Node that matches the specified XPath selectors.
55
+ func QuerySelectorAll (top * Node , selector * xpath.Expr ) []* Node {
56
+ t := selector .Select (CreateXPathNavigator (top ))
57
+ var elems []* Node
58
+ for t .MoveNext () {
59
+ elems = append (elems , (t .Current ().(* NodeNavigator )).cur )
60
+ }
61
+ return elems
62
+ }
63
+
64
+ // QuerySelector returns the first matched XML Node by the specified XPath selector.
65
+ func QuerySelector (top * Node , selector * xpath.Expr ) * Node {
66
+ t := selector .Select (CreateXPathNavigator (top ))
39
67
if t .MoveNext () {
40
- elem = (t .Current ().(* NodeNavigator )).cur
68
+ return (t .Current ().(* NodeNavigator )).cur
41
69
}
42
- return elem
70
+ return nil
43
71
}
44
72
45
73
// NodeNavigator is for navigating JSON document.
0 commit comments