Search code examples
xmlgroovyxmlslurper

Why is the text displayed if the tag is missing in the xml?


You need to read the xml and display only those values where there are INNYL or INNFL tags. But if I do not have any of them in the "Document" or it is empty, then the output is: INNYL INNFL Why is that? I need nothing to be displayed in this case, since there are no values (there is no tag or it is empty).

 def person = new XmlSlurper().parse(new File("C:\\test\\test.xml"))

        person.Document.findAll { p ->
            p.Org.@INNYL != null ||
            p.IPV.@INNFL != null
        }.each { p ->
            println "INNYL ${p.Org.@INNYL} INNFL ${p.IPV.@INNFL}"
        }

I didn't attach XML, as you can create any.


Solution

  • Because @INNYL returns an empty attribute, not null... You can check it by getting the text, and check if they're empty

        person.Document.findAll { p ->
            [email protected]() ||
            [email protected]()
        }.each { p ->
            println "INNYL ${p.Org.@INNYL} INNFL ${p.IPV.@INNFL}"
        }
    

    Or you can use isEmpty() , ie: [email protected]()