github.com/crowdsecurity/crowdsec@v1.6.1/pkg/exprhelpers/xml.go (about) 1 package exprhelpers 2 3 import ( 4 "github.com/beevik/etree" 5 log "github.com/sirupsen/logrus" 6 ) 7 8 var pathCache = make(map[string]etree.Path) 9 10 // func XMLGetAttributeValue(xmlString string, path string, attributeName string) string { 11 func XMLGetAttributeValue(params ...any) (any, error) { 12 xmlString := params[0].(string) 13 path := params[1].(string) 14 attributeName := params[2].(string) 15 if _, ok := pathCache[path]; !ok { 16 compiledPath, err := etree.CompilePath(path) 17 if err != nil { 18 log.Errorf("Could not compile path %s: %s", path, err) 19 return "", nil 20 } 21 pathCache[path] = compiledPath 22 } 23 24 compiledPath := pathCache[path] 25 doc := etree.NewDocument() 26 err := doc.ReadFromString(xmlString) 27 if err != nil { 28 log.Tracef("Could not parse XML: %s", err) 29 return "", nil 30 } 31 elem := doc.FindElementPath(compiledPath) 32 if elem == nil { 33 log.Debugf("Could not find element %s", path) 34 return "", nil 35 } 36 attr := elem.SelectAttr(attributeName) 37 if attr == nil { 38 log.Debugf("Could not find attribute %s", attributeName) 39 return "", nil 40 } 41 return attr.Value, nil 42 } 43 44 // func XMLGetNodeValue(xmlString string, path string) string { 45 func XMLGetNodeValue(params ...any) (any, error) { 46 xmlString := params[0].(string) 47 path := params[1].(string) 48 if _, ok := pathCache[path]; !ok { 49 compiledPath, err := etree.CompilePath(path) 50 if err != nil { 51 log.Errorf("Could not compile path %s: %s", path, err) 52 return "", nil 53 } 54 pathCache[path] = compiledPath 55 } 56 57 compiledPath := pathCache[path] 58 doc := etree.NewDocument() 59 err := doc.ReadFromString(xmlString) 60 if err != nil { 61 log.Tracef("Could not parse XML: %s", err) 62 return "", nil 63 } 64 elem := doc.FindElementPath(compiledPath) 65 if elem == nil { 66 log.Debugf("Could not find element %s", path) 67 return "", nil 68 } 69 return elem.Text(), nil 70 }