0
votes

Given the data model

<outerTag>
    <tagA>
        </tagB>
    </tagA>
    <tagC>
        <interestingContent>
           ...
        </interestingContent>
    </tagC> 
</outerTag>    

I want to move the child nodes of <interestingContent> into <tagB>. I don't know the possible contents of the nodes to move they may have children as well. I'm currently working with GPath and thought something simple like this should work:

outertag.tagC.childNodes().each { node ->
    outerTag.tagA.tagB.appendNode(node)
}

But while I am able to read the names and texts from the nodes, the appendNode does not seem to do the trick. While I could theoretically read attributes, text and name from the children, use it to create a new node, and append that node, I feel like that's unnecessary complecated, especially because it would need to be a recursive function, since the nodes can have childnodes themself.

1

1 Answers

0
votes

your code with minor changes

def outerTag = new XmlParser().parseText('''<outerTag>
    <tagA>
        <tagB/>
    </tagA>
    <tagC>
        <interestingContent a="a">1</interestingContent>
        <interestingContent a="b">2</interestingContent>
    </tagC>
</outerTag>''')

outerTag.tagC[0].children().each { child ->
    outerTag.tagA.tagB[0].append(child)
}
//reset value for tagC
outerTag.tagC[0].setValue("")

println groovy.xml.XmlUtil.serialize(outerTag)