Wednesday, 30 January 2019

Groovy: print first 10 fibonacci numbers


HelloWorld.groovy
previous = 1
current = 1

print previous + " " + current

8.times{
 next =  previous + current
 previous  = current
 current  = next
 print " " + next
}

Output
1 1 2 3 5 8 13 21 34 55


Previous                                                 Next                                                 Home

Groovy: Print all the file names in a directory recursively


Below statement prints all the file names recursively.

HelloWorld.groovy
String directoryPath = "C:\\Users\\Public"

new File(directoryPath).eachFileRecurse { println it }


Previous                                                 Next                                                 Home

Groovy: parse xml file


In groovy parsing xml file is very easy. You can use '.' to access the nested xml elements. You can use @ symbol to access the attribute of an xml element.

employee.xml
<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <employee org = "ABC Corporation">
        <id>1</id>
        <firstname>Siva</firstname>
        <middlename>Krishna</middlename>
        <lastname>Gurram</lastname>
        <age>25</age>
        <salary>80000</salary>
        <married>no</married>
    </employee>
    <employee org = "XYZ Corporation">
        <id>1</id>
        <firstname>Gopi</firstname>
        <middlename>B</middlename>
        <lastname>Battu</lastname>
        <age>29</age>
        <salary>280000</salary>
        <married>yes</married>
    </employee>
</employees>


HelloWorld.groovy
String xmlFilepath = "C:\\Users\\Public\\employee.xml";

def employees = new XmlSlurper().parse(new File(xmlFilepath))

for (employee in employees.employee)
{
 println "${employee.firstname}, ${employee.lastname} work for ${employee.@org}"
}

Output
Siva, Gurram work for ABC Corporation
Gopi, Battu work for XYZ Corporation



Previous                                                 Next                                                 Home