2

I want to parse a xml file during build time in build.gradle file and want to modify some values of xml, i follow this SO question and answer Load, modify, and write an XML document in Groovy but not able to get any change in my xml file. can anyone help me out. Thanks

code in build.gradle :

def overrideLocalyticsValues(String token) {
def xmlFile = "/path_to_file_saved_in_values/file.xml"
def locXml = new XmlParser().parse(xmlFile)

locXml.resources[0].each {
    it.@ll_app_key = "ll_app_key"
    it.value = "123456"
}
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile)))
nodePrinter.preserveWhitespace = true
nodePrinter.print(locXml)
}

xml file :

<resources>
<string name="ll_app_key" translatable="false">MY_APP_KEY</string>
<string name="ll_gcm_sender_id" translatable="false">MY_GCM_SENDER_ID</string>
</resources>
Kapil Rajput
  • 11,429
  • 9
  • 50
  • 65

2 Answers2

5

In your code : Is it right ...? Where is node name and attribute ..?

locXml.resources[0].each {    // Wrongly entered without node name 
    it.@ll_app_key = "ll_app_key"   // Attribute name @name
    it.value = "123456"           // you can't change or load values here
}

You tried to read and write a same file. Try this code which replaces the exact node of the xml file. XmlSlurper provides this facility.

Updated :

import groovy.util.XmlSlurper
import groovy.xml.XmlUtil

def xmlFile = "test.xml"
def locXml = new XmlSlurper().parse(xmlFile)


locXml.'**'.findAll{ if (it.name() == 'string' && it.@name == "ll_app_key") it.replaceBody 12345 }

new File (xmlFile).text = XmlUtil.serialize(locXml)
Bhanuchander Udhayakumar
  • 1,581
  • 1
  • 12
  • 30
0

Groovy has a better method for this than basic replacement like you're trying to do - the SimpleTemplateEngine

static void main(String[] args) {
    def templateEngine = new SimpleTemplateEngine()
    def template = '<someXml>${someValue}</someXml>'
    def templateArgs = [someValue: "Hello world!"]
    println templateEngine.createTemplate(template).make(templateArgs).toString()
}

Output:

<someXml>Hello world!</someXml>

Ben Harris
  • 1,734
  • 3
  • 15
  • 24