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.

<?xml version="1.0"?>
<project name="xmlGradleProject" version = "1.0">
    <modulelist name="ModulesNameList" shortName = "mnl">
        <module name="firstModule" version = "1.1"/>
        <module name="SecondModule" version = "2.1" />
    <description> This is simple xml parser in gradle </description>

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


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.
Other How to dos

, , ,

only 1 comment untill now

  1. Aakar Verma @ 2015-08-19 05:34

    Helped me in knowing how to read the attribute values of their tags in xml. Thanks!

Add your comment now