Copying an XmlNode Between XmlValue Variables
5 min
overview you can copy an xmlnode between xmlvalue variables by cloning the source node and assigning the cloned node to the target value use case use this approach when you need to transfer a list, nested structure, or other xml fragment from one object to another without rebuilding the xml manually example using system xml; // instantiate a service instance and add some test data // this will be our source for the copy serviceinstance srv1 = new serviceinstance(); srv1 data setvalue("selecteditems/@list", "1"); srv1 data addlistvalue("selecteditems/item", "item1"); srv1 data addlistvalue("selecteditems/item", "item2"); // instantiate a service instance // this will be the target for our copy serviceinstance srv2 = new serviceinstance(); // trace before the copy trace writeline(srv2 data formattedxml); // select the node to copy xmlnode sourcenode = srv1 data selectsinglenode("selecteditems"); // clone the source node and set it into the target srv2 data setvalue("selecteditems", sourcenode clonenode(true)); // trace after the copy trace writeline(srv2 data formattedxml); how it works create or retrieve the source xml structure select the node to be copied using selectsinglenode() clone the node using clonenode(true) assign the cloned node to the target using setvalue() the target now contains an independent copy of the original xml structure result before the copy, the target contains no selecteditems node after the copy, the target contains \<selecteditems list="1"> \<item>item1\</item> \<item>item2\</item> \</selecteditems> key points clonenode(true) performs a deep copy, including all child nodes and attributes the source and target become independent after the copy changes made to the target node do not affect the original source node this technique is useful for copying lists, collections, and complex xml structures between objects notes use clonenode(true) when you want to preserve the entire xml hierarchy a shallow clone ( clonenode(false) ) copies only the selected node and excludes child nodes this approach avoids manually recreating xml structures in the target object