如何将xmlns属性添加到根元素?

时间:2014-04-01 06:09:37

标签: c# xml

我必须像下载

一样编写xml文件
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <Status>Enabled</Status>
</VersioningConfiguration>

请任何人帮我写上面的内容。

2 个答案:

答案 0 :(得分:0)

LINQ to XML使这一点变得微不足道 - 您只需指定元素的命名空间,它将自动包含xmlns="..."。你可以给它一个别名,但这有点难。要生成您展示的确切文档,您只需要:

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是迄今为止我使用过的最好的XML API,特别是在其命名空间的处理方面。只要对XmlDocument说不!)

答案 1 :(得分:0)

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