如何在groovy xmlslurper中检查标签是否包含值或子标签?

时间:2018-07-25 11:22:04

标签: 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);

我有类似的要求

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

输入可以是第一位或第二位,其动态不同。如果没有任何迭代或进行单次检查,该如何实现上述条件?

1 个答案:

答案 0 :(得分:1)

尝试此代码:

我希望这段代码可以阐明您的要求。

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
    }
}