Search code examples
groovyxmlslurper

How to check that a tag contains value or child tag in groovy xmlslurper?


def list="<books>
<book>
<title>xx</title>
<year>xxxx</year>
<book>
</books>" (or) 
def list="
<books>
<book> xxxx <book>
</books>";
def books=new XMLSlurper(list);

I have requirment like

if (books.book has value ) do something 
else if(books.book has tag ) do something

Input can be either first or second which differs dynamically. How can I achieve above if condition without any iteration or with single check?.


Solution

  • Try this code :

    i hope this code will clarify your requirement.

    def list1 = "<books><book>xxx</book></books>"
    
    def list2 = "<books><book><new>xxx</new></book></books>"
    
    [list1, list2].each{ text->
    
    def root = new XmlSlurper().parseText(text)
    
    
        if (root.book.children().collect{ it.name()})
        {
            println 'book has children : '+ root.book.children().collect{ it.name()}
        }
        else
        {
            println 'book has value :'+root.book
        }
    }