-
Notifications
You must be signed in to change notification settings - Fork 376
/
xml.go
43 lines (34 loc) · 984 Bytes
/
xml.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
package extraction
import (
"bytes"
"fmt"
"github.com/antchfx/xmlquery"
)
type xmlExtractor struct {
}
func (xe xmlExtractor) extractFromByteSlice(source []byte, xPath string) (interface{}, error) {
reader := bytes.NewBuffer(source)
rootNode, err := xmlquery.Parse(reader)
if err != nil {
return nil, err
}
// returns the first matched element
foundNode, err := xmlquery.Query(rootNode, xPath)
if foundNode == nil || err != nil {
return nil, fmt.Errorf("no match for the xPath: %s", xPath)
}
return foundNode.InnerText(), nil
}
func (xe xmlExtractor) extractFromString(source string, xPath string) (interface{}, error) {
reader := bytes.NewBufferString(source)
rootNode, err := xmlquery.Parse(reader)
if err != nil {
return nil, err
}
// returns the first matched element
foundNode, err := xmlquery.Query(rootNode, xPath)
if foundNode == nil || err != nil {
return nil, fmt.Errorf("no match for this xpath")
}
return foundNode.InnerText(), nil
}