2022-04-29 11:52:23 +00:00
|
|
|
package exprhelpers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/beevik/etree"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
var pathCache = make(map[string]etree.Path)
|
|
|
|
|
2023-03-28 08:49:01 +00:00
|
|
|
// func XMLGetAttributeValue(xmlString string, path string, attributeName string) string {
|
|
|
|
func XMLGetAttributeValue(params ...any) (any, error) {
|
|
|
|
xmlString := params[0].(string)
|
|
|
|
path := params[1].(string)
|
|
|
|
attributeName := params[2].(string)
|
2022-04-29 11:52:23 +00:00
|
|
|
if _, ok := pathCache[path]; !ok {
|
|
|
|
compiledPath, err := etree.CompilePath(path)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Could not compile path %s: %s", path, err)
|
2023-03-28 08:49:01 +00:00
|
|
|
return "", nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|
|
|
|
pathCache[path] = compiledPath
|
|
|
|
}
|
|
|
|
|
|
|
|
compiledPath := pathCache[path]
|
|
|
|
doc := etree.NewDocument()
|
|
|
|
err := doc.ReadFromString(xmlString)
|
|
|
|
if err != nil {
|
|
|
|
log.Tracef("Could not parse XML: %s", err)
|
2023-03-28 08:49:01 +00:00
|
|
|
return "", nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|
|
|
|
elem := doc.FindElementPath(compiledPath)
|
|
|
|
if elem == nil {
|
|
|
|
log.Debugf("Could not find element %s", path)
|
2023-03-28 08:49:01 +00:00
|
|
|
return "", nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|
|
|
|
attr := elem.SelectAttr(attributeName)
|
|
|
|
if attr == nil {
|
|
|
|
log.Debugf("Could not find attribute %s", attributeName)
|
2023-03-28 08:49:01 +00:00
|
|
|
return "", nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|
2023-03-28 08:49:01 +00:00
|
|
|
return attr.Value, nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|
|
|
|
|
2023-03-28 08:49:01 +00:00
|
|
|
// func XMLGetNodeValue(xmlString string, path string) string {
|
|
|
|
func XMLGetNodeValue(params ...any) (any, error) {
|
|
|
|
xmlString := params[0].(string)
|
|
|
|
path := params[1].(string)
|
2022-04-29 11:52:23 +00:00
|
|
|
if _, ok := pathCache[path]; !ok {
|
|
|
|
compiledPath, err := etree.CompilePath(path)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Could not compile path %s: %s", path, err)
|
2023-03-28 08:49:01 +00:00
|
|
|
return "", nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|
|
|
|
pathCache[path] = compiledPath
|
|
|
|
}
|
|
|
|
|
|
|
|
compiledPath := pathCache[path]
|
|
|
|
doc := etree.NewDocument()
|
|
|
|
err := doc.ReadFromString(xmlString)
|
|
|
|
if err != nil {
|
|
|
|
log.Tracef("Could not parse XML: %s", err)
|
2023-03-28 08:49:01 +00:00
|
|
|
return "", nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|
|
|
|
elem := doc.FindElementPath(compiledPath)
|
|
|
|
if elem == nil {
|
|
|
|
log.Debugf("Could not find element %s", path)
|
2023-03-28 08:49:01 +00:00
|
|
|
return "", nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|
2023-03-28 08:49:01 +00:00
|
|
|
return elem.Text(), nil
|
2022-04-29 11:52:23 +00:00
|
|
|
}
|