Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new XDocument from an existing XDocument

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?

like image 508
Bob Tway Avatar asked Jan 20 '11 09:01

Bob Tway


1 Answers

You are looking for the XDocument constructor that takes an XDocument. This will create a deep copy of the passed XDocument.

Sample code:

var foo_original = XDocument.Load("foo.xml");
var foo_copy1 = new XDocument(foo_original);
var foo_copy2 = new XDocument(foo_original);
like image 104
Dono Avatar answered Oct 25 '22 13:10

Dono