Controlling Namespace Serialization

Description Article
Table of Contents
Operations
Parse XML document
How to do it
XElement root = XElement.Parse(
    @"<a:Root xmlns:a='http://www.adventureworks.com'>
        <a:Child>1</a:Child>
      </a:Root>");
Parse XML document: Remove namespace attributes and add it as default namespace
How to do it
XElement root = XElement.Parse(
    @"<a:Root xmlns:a='http://www.adventureworks.com'>
        <a:Child>1</a:Child>
      </a:Root>");

// Remove all namespace attributes..
root.DescendantsAndSelf().Attributes().Where(n => n.IsNamespaceDeclaration).Remove();

// Specify that the namespace will be serialized as the default namespace..
root.Add(new XAttribute("xmlns", "http://www.adventureworks.com"));

Console.WriteLine(root);
<!-- new XML document -->

<Root xmlns="http://www.adventureworks.com">
  <Child>1</Child>
</Root>
Parse XML document: Remove namespace attributes and change prefixes
How to do it
XElement root = XElement.Parse(
    @"<a:Root xmlns:a='http://www.adventureworks.com'
              xmlns:c='http://www.contoso.com'>
        <c:Child>1</c:Child>
      </a:Root>");

// Remove all namespace attributes...
root.DescendantsAndSelf().Attributes().Where(n => n.IsNamespaceDeclaration).Remove();

// Specify prefixes for both namespaces at root...
root.Add(
    new XAttribute(XNamespace.Xmlns + "x", "http://www.adventureworks.com"),
    new XAttribute(XNamespace.Xmlns + "y", "http://www.contoso.com"));

Console.WriteLine(root);
<!-- new XML document -->

<Root xmlns="http://www.adventureworks.com"
      xmlns:y="http://www.contoso.com">
  <y:Child>1</y:Child>
</Root>