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:
XNamespace xmlns = "http://schemas.datacontract.org/2004/07/Widgets";
doc.Root.Name = xmlns + doc.Root.Name.LocalName;
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:
public static void SetDefaultXmlNamespace(this XElement xelem, XNamespace xmlns)
{
if(xelem.Name.NamespaceName == string.Empty)
xelem.Name = xmlns + xelem.Name.LocalName;
foreach(var e in xelem.Elements())
e.SetDefaultXmlNamespace(xmlns);
}
// ...
doc.Root.SetDefaultXmlNamespace("http://schemas.datacontract.org/2004/07/Widgets");
Or, if you prefer a version that does not mutate the existing document:
public XElement WithDefaultXmlNamespace(this XElement xelem, XNamespace xmlns)
{
XName name;
if(xelem.Name.NamespaceName == string.Empty)
name = xmlns + xelem.Name.LocalName;
else
name = xelem.Name;
return new XElement(name,
from e in xelem.Elements()
select e.WithDefaultXmlNamespace(xmlns));
}