Search code examples
c#xml

How to add xmlns attribute to the root element?


I have to write xml file like the fallowing

<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <Status>Enabled</Status>
</VersioningConfiguration>

please any one help me to write like above.


Solution

  • LINQ to XML makes this trivial - you just specify the namespace for the element, and it will include the xmlns="..." automatically. You can give it an alias, but that's slightly harder. To produce the exact document you've shown, you just need:

    XNamespace ns = "http://s3.amazonaws.com/doc/2006-03-01/";
    var doc = new XDocument(
        new XElement(ns + "VersioningConfiguration",
           new XElement(ns + "Status", "Enabled")));
    Console.WriteLine(doc);
    

    LINQ to XML is by far the best XML API I've used, particularly in its handling of namespaces. Just say no to XmlDocument :)