I have a function which takes as an argument an XDocument object.
I need to loop through a number of other objects in a different collection and for each one of those objects, perform some actions on the XDocument. But each iteration of the lopp needs a pristine copy of the original XDocument that’s passed to the function.
However if I just try and perform my operations on the variable that’s passed into the function it behaves like a pointer – so each iteration of the loop receives the XDocument in whatever state it was left at the end of the last iteration which is no use at all.
Obviously I need to make a copy of the Xdocument but I can see no straightforward way of doing this. Trying:
XDocument currentServerXml = XDocumentFromFunction.Document():
And then using currentServerXml instead of XDocumentFromFunction gets me the same copy with the same pointer and the same behaviour.
How can I create a brand new copy of the data for each iteration of the loop?
You are looking for the XDocument constructor that takes an XDocument. This will create a deep copy of the passed XDocument.
Sample code: