Search code examples
jenkinsgroovy

Jenkins...Modify XML Tag value in xml file using Groovy in Jenkins


I am using jenkins for automated deployment.

I needs to modify xml tag value in xml file using groovy script. I am using below groovy code. When I try to edit xml tag value I am receiving error unclassified field xml.uti.node error.

Node xml = xmlParser.parse(new File("c:/abc/test.xml"))
xml.DeployerServer.host[0] = '172.20.204.49:7100'
FileWriter fileWriter = new FileWriter("c:/abc/test.xml")
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(fileWriter))
nodePrinter.setPreserveWhitespace(true)
nodePrinter.print(xml)

I need to modify host tag value and host is available inside DeployerServer tag.

Any help will be much appreciated.


Solution

  • Here is the script, comments in-line:

    //Create file object
    def file = new File('c:/abc/test.xml')
    //Parse it with XmlSlurper
    def xml = new XmlSlurper().parse(file)
    //Update the node value using replaceBody
    xml.DeployerServer.host[0].replaceBody '172.20.204.49:7100'
    //Create the update xml string
    def updatedXml = groovy.xml.XmlUtil.serialize(xml)
    //Write the content back
    file.write(updatedXml)