0

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.

Nerethar
  • 327
  • 2
  • 16

1 Answers1

0

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)
daggett
  • 26,404
  • 3
  • 40
  • 56
  • I don't have this as String but just the GPath so far. Can I still use this solution by converting it anyhow, or does it even needs to be converted? And what purpose are the [0] there? – Nerethar Jan 16 '19 at 12:27
  • string to make code runnable. it does not matter how you built or parsed xml. `[0]` to specify which tag you want to access (you could have several `tagB` inside `tagA`). `outerTag.tagC` returns a list of nodes, but `outerTag.tagC[0]` returns exactly one first node.. – daggett Jan 16 '19 at 13:24