2011-03-24 46 views
0

我正在導入一個XML,然後根據XML中的信息創建一個對象列表。Groovy:使用Closure創建和返回地圖元素

這是我的XML的一個樣本:

<DCUniverse> 
    <SuperHeroes> 
     <SuperHero> 
      <SuperHeroName>SuperMan</SuperHeroName> 
      <SuperHeroDesc>Surviver of Krypton; Son of Jor-el</SuperHeroDesc> 
      <SuperHeroCode>SM</SuperHeroCode> 
      <SuperHeroAttrs> 
       <SuperHeroAttr Name="Strength">All</SuperHeroAttr> 
       <SuperHeroAttr Name="Weakness">Kryptonite</SuperHeroAttr> 
       <SuperHeroAttr Name="AlterEgo">Clark Kent</SuperHeroAttr> 
      </SuperHeroAttrs> 
     </SuperHero> 
     <SuperHero> 
      <SuperHeroName>Batman</SuperHeroName> 
      <SuperHeroDesc>The Dark Knight of Gothom City</SuperHeroDesc> 
      <SuperHeroCode>BM</SuperHeroCode> 
      <SuperHeroAttrs> 
       <SuperHeroAttr Name="Strength">Intellect</SuperHeroAttr> 
       <SuperHeroAttr Name="Weakness">Bullets</SuperHeroAttr> 
       <SuperHeroAttr Name="AlterEgo">Bruce Wayne</SuperHeroAttr> 
      </SuperHeroAttrs> 
     </SuperHero> 
    </SuperHeroes> 
<DCUniverse> 

這裏是我正在創建的對象的Groovy腳本的例子:

class Hero{ 
    def SuperHeroName 
    def SuperHeroDesc 
    def SuperHeroCode 
    def SuperHeroAttrLst = [:] 
    Hero(String name, String desc, String code, attrLst){ 
     this.SuperHeroName=name 
     this.SuperHeroDesc=desc 
     this.SuperHeroCode=code 
     this.SuperHeroAttrLst.putAll(attrLst) 
    } 
} 
def heroList = [] 

def heroDoc = new XmlParser().parse('dossier.xml') 

heroDoc.SuperHeroes.each{ faction -> 
    faction.SuperHero.each{ hero -> 
     heroList += new Hero( hero.SuperHeroName.text(), 
           hero.SuperHeroDesc.text(), 
           hero.SuperHeroCode.text(), 
           hero.SuperHeroAttrs.SuperHeroAttr.each{ attr -> 
            return [ (attr.'@Name') : (attr.text()) ] 
           }) 
    } 
} 

當我運行上面的代碼,我得到以下錯誤:

java.lang.ClassCastException: groovy.util.Node cannot be cast to java.util.Map$Entry 

我有一種強烈的感覺,它與最後一個變量有關e封閉試圖發送給Hero Class Constructor。註釋掉

this.SuperHeroAttrLst.putAll(attrLst) 

英雄構造函數允許腳本至少解析正確。我所要做的是創建一個基於XML的一類,並將其放置在列表中,如:

heroList += new Hero('Batman', 
'The Dark Knight of Gothom City', 
'BM', 
['Strength':'Intellect', 'Weakness':'Bullets', 'AlterEgo':'Bruce Wayne']) 

然而,我的變量類型是不正確的,我不知道有足夠的瞭解Groovy的(或Java的)語法,使這行得通。

任何可以提供的幫助將不勝感激。感謝您的時間。

回答

0

我想你應該改變hero.SuperHeroAttrs.SuperHeroAttr.each{ //blah blah到:

hero.SuperHeroAttrs.inject([:]) { attributes, attr -> 
    attributes[attr.'@Name'] = attr.text() 
    return attributes 
} 
+0

謝謝@CarlosZ! .inject()是工作的完美工具。 – 2011-03-24 15:06:01