2013-06-18 45 views
-1

我有一個小代碼片斷,它循環遍歷節點並獲取其所有屬性。 我可以得到這個工作,如果我設置一個變量來獲取屬性值(除了它周圍有一個怪異的[]]。但我不想冗餘代碼,所以我試圖在循環內設置多個屬性,除了所有返回的是單個值,它不是循環遍歷所有節點。Groovy - Collection僅返回單個值

WORKING

String selectNodeLabel = null 
selectNodeLabel = JcrUtils.getChildNodes("links").collect{ 
    it.getProperty("label").getString() 
} 

單個值

String selectNodeLabel = null 
String selectNodeMeta = null 
String selectNodeFooter= null 
String topicNode = null 

topicNode = JcrUtils.getChildNodes("links").collect{ 
    selectNodeLabel = it.getProperty("label").getString() 
    selectNodeMeta = it.getProperty("meta").getString() 
    selectNodeFooter = it.getProperty("footer").getString() 
} 

感謝您的幫助!

+0

它決不是一個壞主意,看看[收藏API]最後一行(HTTP://groovy.codehaus .org/groovy-jdk/java/util/Collection.html)和[這些有用的信息](http://groovy.codehaus.org/Collections)。 – dmahapatro

+0

我可以得到有關倒票的解釋嗎?很高興解決任何問題。 –

回答

1

嘗試:

def nodeList = JcrUtils.getChildNodes("links").collect{ 
    [ selectNodeLabel : it.getProperty("label").getString() 
    selectNodeMeta : it.getProperty("meta").getString() 
    selectNodeFooter : it.getProperty("footer").getString() ] 
} 

然後,nodeList必應地圖的列表,所以你可以這樣做:

println nodeList*.selectNodeLabel 

打印所有selectNodeLabel值的例子。

解釋您的代碼存在問題... Collect會創建閉包返回的元素列表。代碼的作用是覆蓋selectNode...變量中的值,然後將topicNode設置爲JcrUtils.getChildNodes("links")中每個元素的閉包返回的值。

對於這種情況,topicNode將包含it.getProperty("footer").getString()列表(因爲它是在封閉