How to specify an xmlns for XDocument? How to specify an xmlns for XDocument? xml xml

How to specify an xmlns for XDocument?


The way the XDocument API works with namespace-scoped names is as XName instances. These are fairly easy to work with, as long as you accept that an XML name isn't just a string, but a scoped identifier. Here's how I do it:

var ns = XNamespace.Get("http://example.com");var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));var root = new XElement(ns + "root1", new XElement(ns + "a", "b"));doc.Add(root);

Result:

<root1 xmlns="http://example.com">    <a>b</a></root1>

Note the + operator is overloaded to accept an XNamespace and a String to result in and XName instance.