Bhanuchander Udhayakumar
Bhanuchander Udhayakumar

Reputation: 1621

How to simply add a < root> tag to XML file using groovy?

The xml file is like :

<?xml version="1.0"?>
<first_node>
  <second_node>hai</second_node>
</first_node>

My expected output would be:

<?xml version="1.0"?>
<root>
 <first_node>
   <second_node>hai</second_node>
 </first_node>
</root>

Upvotes: 0

Views: 436

Answers (2)

Rao
Rao

Reputation: 21369

You could achieve using StreamingMarkupBuilderas shown below:

def xmlstring = """<?xml version="1.0"?> <first_node>   <second_node>hai</second_node> </first_node>"""
def xml = new XmlSlurper().parseText(xmlstring)
def newXml = new groovy.xml.StreamingMarkupBuilder().bind {
   root {
     mkp.yield xml
   }
}
println groovy.xml.XmlUtil.serialize(newXml)

You can quickly try it online demo

Upvotes: 3

Marcel F.
Marcel F.

Reputation: 21

You can use XSLT but it's powerful tool if you need only add root tag on start. If you need more than that use XSLT. If you need only use groovy xml dom. Link for groovy and xslt https://www.pleus.net/blog/?p=1448

Upvotes: 0

Related Questions