简体   繁体   中英

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.

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 :)

 XNamespace Name = "http://s3.amazonaws.com/doc/2006-03-01/";
 XDocument doc=new XDocument();
 XElement X1=new XElement(Name+"VersioningConfiguration","" );
 XElement X2=new XElement(Name+"Status","Enabled");
 X1.Add(X2);
 doc.Add(X1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM