File: xml.go

package info (click to toggle)
crowdsec 1.4.6-10.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 18,500 kB
  • sloc: sh: 2,870; makefile: 386; python: 74
file content (64 lines) | stat: -rw-r--r-- 1,491 bytes parent folder | download | duplicates (3)
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
package exprhelpers

import (
	"github.com/beevik/etree"
	log "github.com/sirupsen/logrus"
)

var pathCache = make(map[string]etree.Path)

func XMLGetAttributeValue(xmlString string, path string, attributeName string) string {

	if _, ok := pathCache[path]; !ok {
		compiledPath, err := etree.CompilePath(path)
		if err != nil {
			log.Errorf("Could not compile path %s: %s", path, err)
			return ""
		}
		pathCache[path] = compiledPath
	}

	compiledPath := pathCache[path]
	doc := etree.NewDocument()
	err := doc.ReadFromString(xmlString)
	if err != nil {
		log.Tracef("Could not parse XML: %s", err)
		return ""
	}
	elem := doc.FindElementPath(compiledPath)
	if elem == nil {
		log.Debugf("Could not find element %s", path)
		return ""
	}
	attr := elem.SelectAttr(attributeName)
	if attr == nil {
		log.Debugf("Could not find attribute %s", attributeName)
		return ""
	}
	return attr.Value
}

func XMLGetNodeValue(xmlString string, path string) string {
	if _, ok := pathCache[path]; !ok {
		compiledPath, err := etree.CompilePath(path)
		if err != nil {
			log.Errorf("Could not compile path %s: %s", path, err)
			return ""
		}
		pathCache[path] = compiledPath
	}

	compiledPath := pathCache[path]
	doc := etree.NewDocument()
	err := doc.ReadFromString(xmlString)
	if err != nil {
		log.Tracef("Could not parse XML: %s", err)
		return ""
	}
	elem := doc.FindElementPath(compiledPath)
	if elem == nil {
		log.Debugf("Could not find element %s", path)
		return ""
	}
	return elem.Text()
}