Groovy: Call key of LinkedHashMap through a variable

I have recursive function for make map from xml

def get_map(groovy.xml.slurpersupport.Node Node) {
    nodeRootName = Node.name() 
    if (Node.childNodes().size() == 0) {
        return [(nodeRootName): (Node.text())]
    } else {
        subMap = [(nodeRootName):[]]
        for (subNode in Node.childNodes()) {
            subMap.nodeRootName.add(get_map(subNode))    
        }
        return subMap
    }
}

But I can't call function as .add argument. I have error: java.lang.NullPointerException: Cannot invoke method add() on null object How I can call map.key through a variable as key?

Upvotes: 0

Views: 306

Answers (3)

Alexandr Ivanov
Alexandr Ivanov

Reputation: 399

I do not know what version of Groovy you use. I can not find groovy.xml.slurpersupport.Node class in version 2.5.9. But consider moving creation map out of the for loop.

def get_map(groovy.xml.slurpersupport.Node Node) {
    nodeRootName = Node.name()
    if (Node.childNodes().size() == 0) {
        return [(nodeRootName): (Node.text())]
    } else {
        list = []
        for (subNode in Node.childNodes()) {
            list.add(get_map(subNode))
        }
        return [(nodeRootName):list]
    }
}

Upvotes: 0

It only works like this subMap.(subMap.keySet()[0]).add(get_map(subNode))

Upvotes: 0

Alexandr Ivanov
Alexandr Ivanov

Reputation: 399

Try this:

subMap[nodeRootName].add(get_map(subNode))

Upvotes: 1

Related Questions