Gradle is a great tool for build management. Recently I started using it in my projects. In one of the requirements I had to parse the xml file using gradle. I started looking for help from blog and gradle documents but I hardly found any. I started fiddling around and discovered that it is achievable with the help of xmlParser class.
I would like to share this information with others and here is the example code. The xmlexample.xml contains root element attributes and child elements and their attributes. This example covers reading of all the possible attributes/properties and element’s value.
This is simple xml parser in gradle
and the build.gradle is as following
task parseXml() { def parsedProjectXml = (new XmlParser()).parse('xmlexample.xml') println parsedProjectXml.@name println parsedProjectXml.@version println "ModuleList name : " + parsedProjectXml.modulelist[0].@name + ", shortName : " + parsedProjectXml.modulelist[0].@shortName parsedProjectXml.modulelist.module.each{ module -> println "Name : " + module.@name + ", version : " + module.@version } println parsedProjectXml.description.text() }
for executing the gradle, run the follwoing command.
$ gradle parseXml project Name : xmlGradleProject, version : 1.0 ModuleList name : ModulesNameList, shortName : mnl Name : firstModule, version : 1.1 Name : SecondModule, version : 2.1 This is simple xml parser in gradle :parseXml UP-TO-DATE BUILD SUCCESSFUL Total time: 4.125 secs
you can also download source code from github. Hope this blog helped you in someway. Please feel free to leave your comments or suggestions about the above post or the website.