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.

  • 1
    What does everyone think of using the XMLDOM parser? Source is available for it. Perhaps the function could be added. developer.force.com/codeshare/projectpage?id=a0630000002ahp5AAA
    – tggagne
    Dec 18, 2015 at 14:44
  • @sfdcfox I came across same scenario where while parsing one of my XML( say A), I need to add another XML (say B)present with me as string , as a child node to my elements present in current XML. Do we have any way ? I tried using addChildElement() method, but it adds the second XML as a string rather then as a XML nodes. Nov 29, 2022 at 11:18

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.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .