How to set the default XML namespace for an XDocument

Not sure if this already worked in .net 3.5 or only in 4, but this works fine for me:

XNamespace ns = @"http://mynamespace";
var result = new XDocument(
    new XElement(ns + "rootNode",
        new XElement(ns + "child",
            new XText("Hello World!")
         )
     )
 );

produces this document:

<rootNode xmlns="http://mynamespace">
    <child>Hello World!</child>
</rootNode>

Important is to always use the ns + "NodeName" syntax.

Leave a Comment