[ 
https://issues.apache.org/jira/browse/GROOVY-8206?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17839681#comment-17839681
 ] 

Simon Ceder commented on GROOVY-8206:
-------------------------------------

[~paulk] I have a use case were this matters. I currently have to wrap the 
cloned node in a placeholder in a real world scenario.

My use case is that I receive a big XML file which needs to be preserved for 
history. I also need to split this big XML file into smaller files. To do this 
I am using XmlParser to get and clone the nodes that needs to be split into new 
files. All good so far. Now I also need to edit the new files by replacing some 
of the child nodes. This can't be done without a parent assigned to the child 
node otherwise I receive this error: 
{code:java}
java.lang.UnsupportedOperationException: Replacing the root node is not 
supported {code}
As such I first have to wrap the cloned nodes in a placeholder node before I 
can edit them and save them to a new file. I really don't see the reason for 
the cloned nodes children having no parent set? 

> Groovy clone node with new parent reference in child nodes
> ----------------------------------------------------------
>
>                 Key: GROOVY-8206
>                 URL: https://issues.apache.org/jira/browse/GROOVY-8206
>             Project: Groovy
>          Issue Type: Improvement
>          Components: groovy-jdk
>            Reporter: Manish Yadav
>            Priority: Major
>
> As of now groovy supports clone node feature without storing parent 
> reference(i.e. the new clone nodes) in child nodes.
> We can add following custom methods in some util class to make cloning more 
> advanced :
> 1:
> {code}
> private Node cloneNode(Node node, Node parentNode) {
>     Object newValue = node.value()
>     Node clonedNode = new Node(null, node.name(), new 
> HashMap(node.attributes()), newValue)
>     if (newValue instanceof NodeList) {
>         NodeList nodes = (NodeList) newValue
>         newValue = cloneNodeList(nodes, clonedNode)
>     }
>     clonedNode.setValue(newValue)
>     clonedNode.setParent(parentNode)
>     return clonedNode
> }
> {code}
> 2:
> {code}
> private NodeList cloneNodeList(NodeList nodeList, Node parentNode) {
>     NodeList result = new NodeList(nodeList.size())
>     for (int i = 0; i < nodeList.size(); i++) {
>         Object next = nodeList.get(i)
>         if (next instanceof Node) {
>             result.add(cloneNode((Node) next, parentNode))
>         } else {
>             result.add(next)
>         }
>     }
>     return result
> }
> {code}



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to