Wednesday 30 January 2019

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

No comments:

Post a Comment