xml.go 1.8 KB

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