Search code examples
groovyxmlslurper

Is it possible to parse a text file containing XML-like string using XmlSlurper in Groovy?


I have a method readFileContent which will take an XML file as an input and read the content of the XML file and then outputs a String of XML-like data.

Now, this XML-like String will be the input parameter of another method extractActualData that in turn will parse the XML-like String and produce the actual data as output.

My question is: Is it possible to parse a text file containing XML-like string using XmlSlurper in Groovy?


Solution

  • There is a method in the class calledXmlSlurper.parseText(String str) where you pass a String containing XML body and you can process the result, something like:

    def text = '''
        <list>
            <technology>
                <name>Groovy</name>
            </technology>
        </list>
    '''
    
    def list = new XmlSlurper().parseText(text)
    
    assert list instanceof groovy.util.slurpersupport.GPathResult
    assert list.technology.name == 'Groovy'
    

    Source: http://groovy-lang.org/processing-xml.html

    You can use exact same method inside your extractActualData method.