3

I have an xml that looks like this

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Samples>
  <Sample>
     <Name>
        Sample1
     </Name>
     <Date>
        01/20/2016
     </Date>
  </Sample>
</Samples>

I want to simply change the tag name from "Samples" to "SampleList". How will I do it?

dmahapatro
  • 49,365
  • 7
  • 88
  • 117
user3714598
  • 1,733
  • 5
  • 28
  • 45

1 Answers1

4

replaceNode can be used to rename the node as below:

def xml = '''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Samples>
  <Sample>
     <Name>
        Sample1
     </Name>
     <Date>
        01/20/2016
     </Date>
  </Sample>
</Samples>
'''

def result = new XmlSlurper().parseText(xml)

result.replaceNode { 
    'SampleList' it.children() 
}

groovy.xml.XmlUtil.serialize(result)

replaceNode takes a closure as method parameter which delegates to a builder. Specifically in this case the node is replaced instead of appending it to main document. 'SampleList' it.children() is similar to 'SampleList(it.children())'.

Parsed xml's root element being Samples (which needs replacement), replaceNode was directly done on the result.

dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • hi @dmahapatro, could you explain how replaceNode works? becuase you did not specify what name that you want to be replaced but the code works. Thanks :) – user3714598 Jun 28 '16 at 05:41