簡體   English   中英

Groovy:使用閉包創建和返回地圖元素

[英]Groovy: Using Closure to create and return Map Elements

我正在導入XML,然后根據XML中的信息創建對象列表。

這是我的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

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

this.SuperHeroAttrLst.putAll(attrLst)

在Hero構造函數中,該腳本至少可以正確解析。 我想做的是基於XML創建一個類,並將其放在列表中,例如:

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

但是,我的變量類型輸入不正確,我對Groovy(或Java)的語法了解不足,無法使其正常工作。

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

我認為您應該將hero.SuperHeroAttrs.SuperHeroAttr.each{ //blah blah更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM