Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def xml2json(src) {
- def children = src.children()
- if (children?.size() == 1 && children[0] instanceof String) {
- if (src.attributes()) {
- def attributes = src.attributes()
- def output = [:]
- attributes.each{
- attribute -> output[attribute.key] = attribute.value
- }
- output.value = children[0]
- return output
- } else {
- return children[0]
- }
- }
- // initializing object to be returned.
- def jsonResult = [:];
- //
- children.each{
- child ->
- // // checking is child has siblings of same name.
- def childIsArray = children.findAll{eachChild -> eachChild.name() == child.name()}?.size() > 1
- // if child is array, save the values as array, else as strings.
- if(childIsArray) {
- if (!jsonResult.containsKey(child.name())) {
- if (src.attributes()) {
- def attributes = src.attributes()
- attributes.each{
- attribute -> jsonResult[attribute.key] = attribute.value
- }
- }
- jsonResult[child.name()] = [xml2json(child)]
- } else {
- jsonResult[child.name()] += (xml2json(child))
- }
- } else {
- jsonResult[child.name()] = xml2json(child)
- }
- }
- return jsonResult
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement