Groovy web console

subscribe to the feed Subscribe
to this
site
update xml attribute (via #groovywebconsole)
tweet this snippet Tweet
this
script

update xml attribute

Published 4 months ago by nmrao with tags update xml
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
def xml = """<project name='Common'>
  <service name='name' pattern='something' isReliable='maybe'>
    <receiver name='name' isUsingTwoWaySsl='maybe' isWsRmDisabled='maybe' 
       targetedByTransformation='maybe'>
      <endpoint name='local_tst01' type='123'>URL1</endpoint>
      <endpoint name='local_tst02' type='xyz'>URL2</endpoint>
      <endpoint name='local_tst03'>URL3</endpoint>
      <environment name='dev' default='local_dev' />
      <environment name='tst01' default='test' />
      <environment name='tst02' default='local_tst02' />
    </receiver>
    <operation name='name'>
      <sender>sender</sender>
      <attribute name='operation' type='String'>name</attribute>
    </operation>
  </service>
</project>"""


//Set your endpoint name attribute value and new endpoint url in a map
//This would be flexible to have the respective url
def endpointBinding = ['local_tst01': 'http://example01.com', 'local_tst02': 'http://example02.com', 'local_tst03': 'http://example03.com']
def typeBinding = ['local_tst01': 'type01', 'local_tst02': 'type02', 'local_tst03': 'type03']
pXml = new XmlSlurper().parseText(xml)
//update endpoint value
endpointBinding.collect { k, v -> pXml.'**'.find{it.name() == 'endpoint' && it.@name == k }.replaceBody(v)}

//update type
typeBinding.collect { k, v -> pXml.'**'.find{it.name() == 'endpoint' && it.attributes().get('type') && it.@name == k }?.@type = v}	

println groovy.xml.XmlUtil.serialize( pXml )