Forum Discussion

asn_007's avatar
asn_007
Contributor
7 years ago
Solved

Create Dynamic XML using Groovy & parameterize the arguments

I would like to create a dynamic xml where some of the nodes and their sub nodes repeat based on the number of times I want them to and then the values of each node elements need to be parameterized ...
  • nmrao's avatar
    7 years ago

    Here is how you can do it using Groovy.

     

    Since you have more data, you can put it in a text file as shown below:

     

     

    name1, price1, description1, calories1
    name2, price2, description2, calories2

     

     

    And the Script goes here:

     

     

    //Make sure you pass the data.txt with absolute path in unix style
    def lines = new File('data.txt').readLines()
    def builder = new StreamingMarkupBuilder()
    builder.encoding = 'UTF-8'
    def xml = builder.bind {
        mkp.xmlDeclaration()
    //Use below line if you need name space as needed, remove otherwise
        namespaces << [ns:'http://example/break/fast']
        breakfast_menu {
            day (new Date().format('EEE MMM d yyyy'))
            time( '08:00:00' )
            lines.each { line ->
                def data = line.split(',')*.trim()
                food {
                    name (data[0])
                    price (data[1])
                    description (data[2])
                    calories (data[3])
                }
            }
        }
    }
    
    def updatedXml = groovy.xml.XmlUtil.serialize(xml)
    log.info updatedXml

     

     

    Output

     

    <?xml version="1.0" encoding="UTF-8"?>
    <breakfast_menu xmlns:ns="http://example/break/fast">
      <day>Thu Apr 27 2017</day>
      <time>08:00:00</time>
      <food>
        <name>name1</name>
        <price>price1</price>
        <description>description1</description>
        <calories>calories1</calories>
      </food>
      <food>
        <name>name2</name>
        <price>price2</price>
        <description>description2</description>
        <calories>calories2</calories>
      </food>
    </breakfast_menu>
  • nmrao's avatar
    nmrao
    7 years ago

    asn_007,

    Ignore the first row. Haven't tried, Can you give a try ?

            lines.eachWithIndex { line, index ->
                if (index) {
                	def data = line.split(',')*.trim()
                	food {
                	    name (data[0])
                	    price (data[1])
                	    description (data[2])
                	    calories (data[3])
                	}
                }	    	
            }