Achin
Achin

Reputation: 1252

Groovy - Modify xml file value

I have an XML file and I am pasting my xml file below. I want to change the value of splash_color using a groovy script. I have tried to parse it but not able to succeed. XML

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="splash_color">#D3B61A</color>
</resources>

Groovy Code:

def xmlFile = "$androidWorkingDirPath/app/src/main/res/values/colors.xml"
    def xml = new XmlParser().parse(xmlFile)
    xml.color[0].each {
        //it.@name = "test2"
        //it.value = "test2"
        println("it.value=$it.value")
        println("it.value=$it.value.name")
    }
    new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).println("Xmlvalue=$xml")

Upvotes: 1

Views: 1849

Answers (1)

ou_ryperd
ou_ryperd

Reputation: 2133

The below works.

def xmlFile = '''<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <color name="splash_color">#D3B61A</color>
</resources>
'''

You can use XmlUtil.serialize instead of new XmlNodePrinter(new PrintWriter(new FileWriter...

import groovy.xml.XmlUtil

I'm using parseText() because in this example I'm not reading from a file

def resources = new XmlParser().parseText(xmlFile)

You don't have to use [0] here, but if there are more nodes with the same name, use findAll()

resources.color.each { 

Use ${} to interpolate variables in strings

    println "it.value=${it.value}" 
    println "it.name=${it.@name}"
}

println XmlUtil.serialize(resources)

You can pipe that to a file.

For the replacement of a node, see this

Upvotes: 1

Related Questions