I have a need to merge one XML document into another. I'm hoping for a more direct way than the one I've come up with.

Given two documents where I want to put B inside A, I can convert B to a string, surround the string with a new node, then parse it into A, then being adding new nodes to A.

What I'd prefer is something like:


That would be a thing of beauty, but I don't see an addXmlNode in:


2 Answers 2


Using the Dom.Document interface, there's no way to append a node arbitrarily as a child to another node. You could write such a function, though, by accepting two nodes in a function, the target and the source, and recursively adding the source to the target:

void addChild(Dom.XmlNode target, Dom.XmlNode source) {

This, as you might imagine, would devolve into a complex branching of various node types (regular nodes, text nodes, and comment nodes). This function would have to call itself recursively, copying every piece of data as it went along. It would be verbose, and very CPU hungry, unlike a native solution would be, if one existed. Instead, simply use string concatenation to copy the nodes directly. Your solution is currently the best available option in the language.


You could use a JAXP identity transformer:

Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(sourceNode), new DOMResult(targetNode));

(Sorry, just realised this is Apex rather than Java. Don't know if this solution works in Apex.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.