@@ -13,33 +13,61 @@ func CreateXPathNavigator(top *Node) *NodeNavigator {
1313 return & NodeNavigator {cur : top , root : top }
1414}
1515
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 .
1717func Find (top * Node , expr string ) []* Node {
18- exp , err := xpath . Compile ( expr )
18+ nodes , err := QueryAll ( top , expr )
1919 if err != nil {
2020 panic (err )
2121 }
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 )
2630 }
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
2842}
2943
30- // FindOne searches the Node that matches by the specified XPath expr,
44+ // Query searches the Node that matches by the specified XPath expr,
3145// and returns first element of matched.
32- func FindOne (top * Node , expr string ) * Node {
46+ func Query (top * Node , expr string ) ( * Node , error ) {
3347 exp , err := xpath .Compile (expr )
3448 if err != nil {
35- panic ( err )
49+ return nil , err
3650 }
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 ))
3967 if t .MoveNext () {
40- elem = (t .Current ().(* NodeNavigator )).cur
68+ return (t .Current ().(* NodeNavigator )).cur
4169 }
42- return elem
70+ return nil
4371}
4472
4573// NodeNavigator is for navigating JSON document.
0 commit comments