Home > Net >  How to add list of Nodes in existing Node Xml in groovy
How to add list of Nodes in existing Node Xml in groovy

Time:09-20

I have such a XML structure, with list of 'attachments', and I want iterate incoming List<String> files and create a groovy.util.Node for each of them and then return the builded Node. In code below I use only the fist element from list(base64 file), but I want to create attachments dynamically based on array size. I am new in groovy and can't find the way how to expand the Node properly.

import groovy.abi.XML

class TestService {

    Node buildNode(List<String> files) {
        Node node = XML.builder().
                "sab:sendExternalEmail"("xmlns:sab": "http://sab/") {
                    "sab:to"('[email protected]')
                    "sab:subject"('Reply')
                    "sab:body"('Body')
                    "sab:from"('[email protected]')
                    "sab:attachments"() {
                        "sab:attachment"() {
                            "sab:fileName"('file1')
                            "sab:fileBase64"(files[0])
                        }
                    }
                }
    }
}

CodePudding user response:

just to give you an idea how to work with builders:

import groovy.util.NodeBuilder
import groovy.xml.XmlUtil


def attachments = [
    "name 1": "content 1",
    "name 2.txt": "content 2"
]

def xml = new NodeBuilder().a{
  for(a in attachments){
    attacchment{
      fileName(a.key)
      fileBase64(a.value)
    }
  }
}

println XmlUtil.serialize(xml)

result:

<?xml version="1.0" encoding="UTF-8"?><a>
  <attacchment>
    <fileName>name 1</fileName>
    <fileBase64>content 1</fileBase64>
  </attacchment>
  <attacchment>
    <fileName>name 2.txt</fileName>
    <fileBase64>content 2</fileBase64>
  </attacchment>
</a>
  • Related