forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxml_document.go
73 lines (57 loc) · 1.88 KB
/
xml_document.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package xpath
import (
"strings"
"github.com/antchfx/xmlquery"
path "github.com/antchfx/xpath"
)
type xmlDocument struct{}
func (d *xmlDocument) Parse(buf []byte) (dataNode, error) {
return xmlquery.Parse(strings.NewReader(string(buf)))
}
func (d *xmlDocument) QueryAll(node dataNode, expr string) ([]dataNode, error) {
// If this panics it's a programming error as we changed the document type while processing
native, err := xmlquery.QueryAll(node.(*xmlquery.Node), expr)
if err != nil {
return nil, err
}
nodes := make([]dataNode, 0, len(native))
for _, n := range native {
nodes = append(nodes, n)
}
return nodes, nil
}
func (d *xmlDocument) CreateXPathNavigator(node dataNode) path.NodeNavigator {
// If this panics it's a programming error as we changed the document type while processing
return xmlquery.CreateXPathNavigator(node.(*xmlquery.Node))
}
func (d *xmlDocument) GetNodePath(node, relativeTo dataNode, sep string) string {
names := make([]string, 0)
// If these panic it's a programming error as we changed the document type while processing
nativeNode := node.(*xmlquery.Node)
nativeRelativeTo := relativeTo.(*xmlquery.Node)
// Climb up the tree and collect the node names
n := nativeNode.Parent
for n != nil && n != nativeRelativeTo {
nodeName := d.GetNodeName(n, sep, false)
names = append(names, nodeName)
n = n.Parent
}
if len(names) < 1 {
return ""
}
// Construct the nodes
nodepath := ""
for _, name := range names {
nodepath = name + sep + nodepath
}
return nodepath[:len(nodepath)-1]
}
func (d *xmlDocument) GetNodeName(node dataNode, _ string, _ bool) string {
// If this panics it's a programming error as we changed the document type while processing
nativeNode := node.(*xmlquery.Node)
return nativeNode.Data
}
func (d *xmlDocument) OutputXML(node dataNode) string {
native := node.(*xmlquery.Node)
return native.OutputXML(false)
}