Search code examples
groovydeclarationxmlslurper

Groovy XMLSlurper Parse Values


I am so close to getting my code completed. I would like to get only the values in an array. Right now I am getting XML declaration plus the line.

Here's my code:

import groovy.xml.XmlUtil

def serverList = new 
XmlSlurper().parse("/app/jenkins/jobs/firstsos_servers.xml")

def output = []
serverList.Server.find { it.@name == SERVER}.CleanUp.GZIP.File.each{
     output.add(XmlUtil.serialize(it))
}

return output

Here is my XML File:

<ServerList>
    <Server name="testserver1">
            <CleanUp>
                    <GZIP>
                            <File KeepDays="30">log1</File>
                            <File KeepDays="30">log1.2</File>
                    </GZIP>
            </CleanUp>
    </Server>
    <Server name="testserver2">
            <CleanUp>
                    <GZIP>
                            <File KeepDays="30">log2</File>
                    </GZIP>
            </CleanUp>
    </Server>
    <Server name="testserver3">
            <CleanUp>
                    <GZIP>
                            <File KeepDays="30">log3</File>
                    </GZIP>
            </CleanUp>
    </Server>

When I select testserver1 my output should be:

['log1','log1.2']

What I am getting is this:

<?xml version="1.0" encoding="UTF-8"?><File KeepDays="30">log1</File>
<?xml version="1.0" encoding="UTF-8"?><File KeepDays="30">log2</File>

Solution

  • You need not require to use XmlUtil.serialize()

    Here is what you need and following inline comments.

    //Define which server you need
    def SERVER = 'testserver1'
    //Pass the 
    def serverList = new 
    XmlSlurper().parse("/app/jenkins/jobs/firstsos_servers.xml")
    
    //Get the filtered file names
    def output = serverList.Server.findAll{it.@name == SERVER}.'**'.findAll{it.name() == 'File'}*.text()
    
    println output
    return output
    

    Output:enter image description here

    You can quickly try online Demo