Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Node vs Node List

Tags:

groovy

I am having difficulty adding a node deeper in an xml structure. I am missing something between and node and nodeList. Any help would be greatly appreciated.

def xml='''<Root id="example" version="1" archived="false">
<Item name="one" value="test"/>
<Item name="two" value="test2"/>
<Item name="three" value="test3"/>
<AppSettings Name="foo" Id="foo1">
    <roles>foo</roles>
</AppSettings>
<AppSettings Name="bar" Id="bar1">
    <Item name="blue" value=""/>
    <Item name="green" value=""/>
    <Item name="yellow" value=""/>
    <Roles>
        <Role id="A"/>
        <Role id="B"/>
        <Role id="C"/>
    </Roles>
</AppSettings>
</Root>'''

root = new XmlParser().parseText(xml)
def appSettings = root.'AppSettings'.find{it.@Name == "bar"}.'Roles'
appSettings.appendNode('Role', [id: 'D'])


def writer = new StringWriter()
def printer = new XmlNodePrinter(new PrintWriter(writer))
printer.preserveWhitespace = true
printer.print(root)
String result = writer.toString()

println result

Error

groovy.lang.MissingMethodException: No signature of method: groovy.util.NodeList.appendNode() is applicable for argument types: (java.lang.String, java.util.LinkedHashMap) values: [Role, [id:D]]
like image 416
zuichuan Avatar asked Aug 08 '12 23:08

zuichuan


1 Answers

This line here:

def appSettings = root.'AppSettings'.find{it.@Name == "bar"}.'Roles'

is returning you a NodeList (containing a single node), so you want to call appendNode on the contents of this list, not on the list itself.

This can be done either by:

appSettings*.appendNode('Role', [id: 'D'])

Which will call appendNode on every element of the list, or by:

appSettings[0]?.appendNode('Role', [id: 'D'])

Which will call appendNode on the first element of the list (if there is a first element thanks to the null-safe operator ?).

like image 159
tim_yates Avatar answered Nov 15 '22 09:11

tim_yates