Matt Howells
Matt Howells

Reputation: 41266

LINQ to XML: How to clone nodes while retaining annotations?

Try this:

var doc1 = XDocument.Load(@"C:\any.xml", LoadOptions.SetLineInfo);
var doc2 = new XDocument(doc1);

doc2 no longer has any line number information. Digging in with Reflector, I can see that when the nodes are cloned from doc1 to doc2 this does not preserve the annotations on the XObject base type, which includes the line number information accessible via IXmlLineInfo. Nor does it retain the BaseUri, which I also need.

Any ideas how I can clone the document while preserving line numbers? I found this but it doesn't preserve BaseUri and is a bit of a hack.

Upvotes: 2

Views: 169

Answers (2)

Patrik
Patrik

Reputation: 188

This retains the LineInfo at least (I didn't try the BaseUri as I didn't need it):

using (var xmlReader = doc1 .CreateReader())
   doc2 = XDocument.Load(xmlReader, LoadOptions.SetLineInfo);

Upvotes: 1

Jeff Yates
Jeff Yates

Reputation: 62387

You could save it into a memory stream and then reload it into a new instance of XDocument.

Upvotes: 0

Related Questions