Search code examples
javadomcloneappendchild

Append cloned child node to cloned node


Presume the following XML:

<outer>
    <entity>
        <id>123</id>
        <subnode1>
        <subnode2>
    </entity>
    <entity>
        <id>124</id>
        <subnode1>
        <subnode2>
    </entity>
</outer>

Overall, I want to split the entity nodes into separate files. I have extracted the entity nodes and stored them within a Map with the corresponding text value as map key. This is absolutely fine for me.

Now I want to write the snippets into new XML files (the IDs serving as file names). I need to keep the outer tags. Therefore, I call the following method to get the outer nodes:

private static Node cloneEmbeddingAncestors(final Node aItem) {
    Node parent = aItem.getParentNode();
    if (parent.equals(((Element) aItem).getOwnerDocument())) {
        // we've reached top level
        return aItem.cloneNode(false);
    }
    Node clone = cloneEmbeddingAncestors(parent);
    return clone.appendChild(aItem.cloneNode(false));
}

While debugging the last line of that method, I get:

  • clone : "[outer: null]" (looks good)
  • aItem : "[entity: null]" (looks good as well)
  • aItem.cloneNode(false) : "[entity: null]" (looks good as well)

But: the whole expression

  • clone.appendChild(aItem.cloneNode(false))

also delivers "[entity: null]"?!? (The resulting XML snippets also only reveal an "entity" tag. I would expect some "outer" tag in the file resp. "outer" node in my debugging display.)

Now, why is that? Any help is very much appeciated! Thanks!


Solution

  • I think I've got it. My mistake was to call appendChild() within the last return statement. appendChild() returns a Node, but the inner one (the child, not the parent). The idea of this method was to recursively return the outer (parent) node, of course. So if I replace the last code line by:

    Node clone = cloneEmbeddingAncestors(parent);
    clone.appendChild(aItem.cloneNode(false));
    return clone;
    

    ...everything works as designed. Hope that helps others one day.