3

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:

some-element-of-a.addXmlNode(some-element-of-b.removeChild(aChildNode));

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

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_xml_dom_xmlnode.htm

2 Answers 2

3

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
0

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.