How can I set the default namespace of an existing XDocument (so I can deserialize it with DataContractSerializer). I tried the following:
var doc = XDocument.Parse("<widget/>");
var attrib = new XAttribute("xmlns",
"http://schemas.datacontract.org/2004/07/Widgets");
doc.Root.Add(attrib);
The exception I get is is The prefix '' cannot be redefined from '' to 'http://schemas.datacontract.org/2004/07/Widgets' within the same start element tag.
Any ideas?
It seems that Linq to XML does not provide an API for this use case (disclaimer: I didn’t investigate very deep). If change the namespace of the root element, like this:
Only the root element will have its namespace changed. All children will have an explicit empty xmlns tag.
A solution could be something like this:
Or, if you prefer a version that does not mutate the existing document: