Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. def xml2json(src) {
  2. def children = src.children()
  3.  
  4. if (children?.size() == 1 && children[0] instanceof String) {
  5. if (src.attributes()) {
  6. def attributes = src.attributes()
  7. def output = [:]
  8. attributes.each{
  9. attribute -> output[attribute.key] = attribute.value
  10. }
  11. output.value = children[0]
  12. return output
  13. } else {
  14. return children[0]
  15. }
  16. }
  17.  
  18. // initializing object to be returned.
  19. def jsonResult = [:];
  20. //
  21. children.each{
  22. child ->
  23. // // checking is child has siblings of same name.
  24. def childIsArray = children.findAll{eachChild -> eachChild.name() == child.name()}?.size() > 1
  25. // if child is array, save the values as array, else as strings.
  26. if(childIsArray) {
  27. if (!jsonResult.containsKey(child.name())) {
  28. if (src.attributes()) {
  29. def attributes = src.attributes()
  30. attributes.each{
  31. attribute -> jsonResult[attribute.key] = attribute.value
  32. }
  33. }
  34. jsonResult[child.name()] = [xml2json(child)]
  35. } else {
  36. jsonResult[child.name()] += (xml2json(child))
  37. }
  38. } else {
  39. jsonResult[child.name()] = xml2json(child)
  40. }
  41. }
  42. return jsonResult
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement