-
Notifications
You must be signed in to change notification settings - Fork 8
/
xmlpath.go
44 lines (40 loc) · 1.07 KB
/
xmlpath.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package forest
import (
"bytes"
"io/ioutil"
"net/http"
"gopkg.in/xmlpath.v2"
)
// XMLPath returns the value found by following the xpath expression in a XML document (payload of response).
func XMLPath(t T, r *http.Response, xpath string) interface{} {
if r == nil {
logfatal(t, sfatalf("XMLPath: no response to read body from"))
return nil
}
if r.Body == nil {
logfatal(t, sfatalf("XMLPath: no response body to read"))
return nil
}
path, err := xmlpath.Compile(xpath)
if err != nil {
logerror(t, serrorf("XMLPath: invalid xpath expression:%v", err))
return nil
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
logerror(t, serrorf("XMLPath: unable to read response body"))
return nil
}
root, err := xmlpath.Parse(bytes.NewReader(data))
// put the body back for re-reads
r.Body = ioutil.NopCloser(bytes.NewReader(data))
if err != nil {
logerror(t, serrorf("XMLPath: unable to parse xml:%v", err))
return nil
}
if value, ok := path.String(root); ok {
return value
}
logerror(t, serrorf("XMLPath: no value for path: %s", xpath))
return nil
}